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]
]
這題我一拿到就感覺應該用DFS保護現場那套來做,但沒寫出來,因為不知道remove在哪操作。
參考了code ganker的代碼調試了一陣子AC了。
public class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if (root == null) return res;
List<Integer> cell = new ArrayList<>();
cell.add(root.val);
helper(root, sum - root.val, cell);
return res;
}
private void helper(TreeNode root, int sum, List<Integer> cell) {
if (root == null) return;
if (root.left == null && root.right == null && 0 == sum) {
res.add(new ArrayList<>(cell));
//相當于else
return;
}
if (root.left != null ) {
cell.add(root.left.val);
helper(root.left, sum - root.left.val, cell);
cell.remove(cell.size() - 1);
}
if (root.right != null ) {
cell.add(root.right.val);
helper(root.right, sum - root.right.val, cell);
cell.remove(cell.size() - 1);
}
}
}
需要注意的地方:
- 這題跟上題不一樣,它先把root加進初始cell表里去,然后才去遞歸找left和right。為什么不能直接把root放進去,我想是因為不好判斷,因為
if (root.left != null && sum > 0) {
cell.add(root.left.val);
helper(root.left, sum - root.left.val);
cell.remove(cell.size() - 1);
}
這三行是套路,不能在套路外面add node啊。
第二是要在root為null的時候和滿足條件之后就return(廢話)。
第三是
res.add(new ArrayList<>(cell));
這句話不能用res.add(cell); cell = new ArrayList<>();這兩句來代替,因為這是dfs啊,后面還要保護現場呢,你找到一個結果之后它要在你原先的結果后面remove的,如果new了,后面remove的時候直接就out of bounds -1了。