首页 > 其他 > 详细

剑指 Offer 34. 二叉树中和为某一值的路径

时间:2021-02-23 23:20:22      阅读:25      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

思路:前序遍历

  dfs前序遍历二叉树,记录每条路径是否满足和为sum,不满足则删去该结点,回溯到上一个结点。

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    LinkedList<List<Integer>> res = new LinkedList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        helper(root, sum);
        return res;
    }
    void helper(TreeNode root, int sum){
        if (root == null)
            return;
        path.add(root.val);
        sum -= root.val;
        if (sum == 0 && root.left == null && root.right == null)
            res.add(new LinkedList(path));
        helper(root.left, sum);
        helper(root.right, sum);
        path.removeLast();
    }
}

需注意的点:

  记录路径时若直接执行 res.add(path) ,则是将 path 对象加入了 res ;后续 path 改变时, res 中的 path 对象也会随之改变。

  正确做法:res.add(LinkedList(path)) ,相当于复制了一个 path 并加入到 res 。

 

剑指 Offer 34. 二叉树中和为某一值的路径

原文:https://www.cnblogs.com/zccfrancis/p/14438092.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!