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]
]

這道題犯了一個(gè)嚴(yán)重的新手錯(cuò)誤,在每次找到path中元素和 == sum的時(shí)候, 寫成了res.add(path)。 可是因?yàn)閎acktracking, 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);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容