LeetCode: Path Sum II

LeetCode: Path Sum II

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

/**
* Created by hzhou on 4/22/15. [email protected]
*/
public class PathSumII {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) {
return result;
}
List<Integer> crt = new ArrayList<Integer>();
helper(root, crt, result, sum);
return result;
}
private void helper(TreeNode root, List<Integer> crt, List<List<Integer>> result, int target) {
if (root == null) {
return;
}
crt.add(root.val);
if (root.left == null && root.right == null) {
if (root.val == target) {
List<Integer> tmp = new ArrayList<Integer>(crt);
result.add(tmp);
}
} else {
if (root.left != null) {
helper(root.left, new ArrayList<Integer>(crt), result, target - root.val);
}
if (root.right != null) {
helper(root.right, crt, result, target - root.val);
}
}
}
}