/
PathSumII.java
47 lines (43 loc) · 1.27 KB
/
PathSumII.java
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
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<List<Integer>> mList = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<Integer> path = new ArrayList<>();
traverse(root, path, 0, sum);
return mList;
}
public void traverse(TreeNode root, List<Integer> path, int cSum, int sum) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
int temp = root.val + cSum;
if (temp == sum) {
path.add(root.val);
mList.add(path);
}
return;
}
List<Integer> lPath = new ArrayList<>();
List<Integer> rPath = new ArrayList<>();
cSum += root.val;
if (root.left != null) {
lPath.addAll(path);
lPath.add(root.val);
traverse(root.left, lPath, cSum, sum);
}
if (root.right != null) {
rPath.addAll(path);
rPath.add(root.val);
traverse(root.right, rPath, cSum, sum);
}
}
}