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]
]
recursion解法,树的解法比较固定,分为base case和recursion rule,然后定好参数,在需要的时候调用自身即可。
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
helper(res, root, new ArrayList<Integer>(), sum);
return res;
}
public void helper(List<List<Integer>> res, TreeNode root, ArrayList<Integer> path, int sum) {
//base case: leaf
if (root.left == null && root.right == null) {
if (root.val == sum) {
path.add(root.val);
res.add(new ArrayList<Integer>(path));
path.remove(path.size() - 1);
}
return;
}
//recursion rule: non-leaf
path.add(root.val);
if (root.left != null) helper(res, root.left, path, sum - root.val);
if (root.right != null) helper(res, root.right, path, sum - root.val);
path.remove(path.size() - 1);
return;
}