113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

         5
         / \
        4   8
       /   / \
      11  13  4
     /  \    / \
    7    2  5   1

return

[
 [5,4,11,2],
 [5,8,4,5]
]

这道题犯了一个严重的新手错误,在每次找到path中元素和 == sum的时候, 写成了res.add(path)。 可是因为backtracking, path最终还是会回到空List. 这样的话不管什么输出,输入都是类似[[],[], ...]这样的。 一定要记得res.add(new ArrayList<>(path)). 这样的话,之后不管path如何变动,是不会影响res里面加的path的。

Screen Shot 2017-09-04 at 6.28.33 PM.png
Screen Shot 2017-09-04 at 6.28.38 PM.png
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        helper(root, sum, path, res);
        return res;
    }
    
    private void helper(TreeNode root, int sum, List<Integer> path, List<List<Integer>> res){
        if (root == null){
            return;
        }
        path.add(root.val);
        if (root.left == null && root.right == null){
            int pathSum = 0;
            for (int i = 0; i < path.size(); i++){
                pathSum += path.get(i);
            }
            if (pathSum == sum){
                res.add(new ArrayList<Integer>(path));
            }
        }
        helper(root.left, sum, path, res);
        helper(root.right, sum, path, res);
        path.remove(path.size() - 1);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容