Leetcode257二叉树所有路径及路径和

本文介绍两种方法求解二叉树所有路径及路径和的问题。方法一采用广度优先搜索,利用双队列记录节点和路径;方法二使用深度优先搜索递归实现。此外,还提供了一种计算所有路径数值和的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目一:二叉树所有路径

/**
 * 
 ClassName: LeetCode257SumTree <br/> 
 Function: <br/>
 *
 *  给定一个二叉树,返回所有从根节点到叶子节点的路径。
 *
 *  说明: 叶子节点是指没有子节点的节点。
 *
 *  输入:
 *
 *    1
 *  /   \
 * 2     3
 *  \
 *   5
 *
 * 输出: ["1->2->5", "1->3"]
 *
 * 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
 *
 * @author zhenxing.liu
 * @date 2020/12/12
 */

分析

  • 方法一:使用两个队列广度优先搜索,一个队列搜索,一个队列记录路径。

  • 方法二:深度优先搜索

参考官方解法(有图形描述很赞):二叉树的所有路径

代码

  • 方法一:使用两个队列广度优先搜索
 public static List<String> treePaths(TreeNode root){
        if(root == null){
            return null;
        }
        List<String> result = new ArrayList<>();
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        Queue<String> pathQueue = new LinkedList<>();
        nodeQueue.offer(root);
        pathQueue.offer(String.valueOf(root.value));
        while(root != null && !nodeQueue.isEmpty()){
            TreeNode node = nodeQueue.poll();
            String path = pathQueue.poll();
            if(node.left == null && node.right == null){
                result.add(path);
            }else{
                if(node.left != null){
                    pathQueue.offer(new StringBuilder(path).append("->").append(node.left.value).toString());
                    nodeQueue.offer(node.left);
                }
                if(node.right != null){
                    pathQueue.offer(new StringBuilder(path).append("->").append(node.right.value).toString());
                    nodeQueue.offer(node.right);
                }
            }
        }
        return result;
    }
  • 方法二:深度搜索递归实现
public static List<String> binaryTreePaths(TreeNode root) {
        List<String> paths = new ArrayList<>();
        constructPaths(root, "", paths);
        return paths;
    }

    /**
     * 深度优先搜索
     * @param root
     * @param path
     * @param paths
     */
    public static void constructPaths(TreeNode root, String path, List<String> paths) {
        if (root != null) {
            StringBuffer pathSB = new StringBuffer(path);
            pathSB.append(root.value);
            if (root.left == null && root.right == null) {  // 当前节点是叶子节点
                paths.add(pathSB.toString());  // 把路径加入到答案中
            } else {
                pathSB.append("->");  // 当前节点不是叶子节点,继续递归遍历
                constructPaths(root.left, pathSB.toString(), paths);
                constructPaths(root.right, pathSB.toString(), paths);
            }
        }
    }

题目一变形: 所有路径和

题目描述

	 * 节点为(0-9* 求节点路径和,1->3->5 则表示 135* 路径和:124 + 135 + 136 = 395

分析

用层次遍历,记录路径时到下一层乘以10

代码

public static int sumTreePaths(TreeNode root){
        if(root == null){
            return 0;
        }
        int result = 0;
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        Queue<Integer> pathQueue = new LinkedList<>();
        nodeQueue.offer(root);
        pathQueue.offer(root.value);
        while(root != null && !nodeQueue.isEmpty()){
            TreeNode node = nodeQueue.poll();
            int path = pathQueue.poll();
            if(node.left == null && node.right == null){
                result += path;
            }else{
                if(node.left != null){
                    pathQueue.offer(path * 10 + node.left.value);
                    nodeQueue.offer(node.left);
                }
                if(node.right != null){
                    pathQueue.offer(path * 10 + node.right.value);
                    nodeQueue.offer(node.right);
                }
            }
        }
        return result;
    }

meituan

结果


/**
         * init tree  1 2 3 4 null 5 6
         *         1
         *     2      3
         *  4  null 5   6
         * @return
         */
public static void main(String[] args) {
        TreeNode root = TreeNode.initTree();
        System.out.println(treePaths(root));
        System.out.println(binaryTreePaths(root));
        System.out.println(sumTreePaths(root));
    }
[1->2->4, 1->3->5, 1->3->6]
[1->2->4, 1->3->5, 1->3->6]
395

参考资料

题目一参考:二叉树的所有路径

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值