1、链接: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 andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
2、思路:和上一道题一样:前序遍历;
3、代码:
public class Solution {
private ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
List<Integer> cur = new ArrayList<Integer>();
preOrder(root, cur, sum, 0);
return res;
}
private void preOrder(TreeNode root, List<Integer> cur, int sum, int pathsum) {
if(root == null)
return ;
pathsum += root.val;
cur.add(root.val);
if(root.left == null && root.right == null && sum == pathsum){
res.add(new ArrayList<Integer>(cur));
}
preOrder(root.left, cur, sum, pathsum);
preOrder(root.right, cur, sum, pathsum);
cur.remove(cur.size() - 1);
}
}