-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
47 lines (39 loc) · 1.34 KB
/
Solution.java
File metadata and controls
47 lines (39 loc) · 1.34 KB
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 {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null)
return result;
Stack<Integer> path = new Stack<Integer>();
preOrder(root, path, result, 0, sum);
return result;
}
private final void preOrder(TreeNode node, Stack<Integer> path, List<List<Integer>> result, int currSum, int expectedSum) {
path.push(node.val);
currSum += node.val;
if (node.left == null && node.right == null && currSum == expectedSum) {
if (currSum == expectedSum) {
List<Integer> pathList = new ArrayList<Integer>();
for (int val : path) {
pathList.add(val);
}
result.add(pathList);
}
}
if (node.left != null) {
preOrder(node.left, path, result, currSum, expectedSum);
}
if (node.right != null) {
preOrder(node.right, path, result, currSum, expectedSum);
}
path.pop();
}
}