113.Path Sum II

Question

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

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

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

Return:

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

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<List<Integer>> res = new ArrayList<>() ;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<Integer> list = new ArrayList<>();
pathSum2(root, sum, list);
return res;
}
public void pathSum2(TreeNode root, int sum, List<Integer> resList){
if(root == null)
return;
if(root.left == null && root.right == null && root.val == sum){ // leaf
resList.add(root.val);
res.add(resList);
return;
}
resList.add(root.val);
List<Integer> resnext = new ArrayList(resList);
pathSum2(root.left, sum-root.val, resnext);
resnext = new ArrayList(resList);
pathSum2(root.right, sum-root.val, resnext);
}
}

Time complexity: $O(n)$

Space complexity: $O(n)$