-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRootLeafSumPathFinder.java
67 lines (51 loc) · 1.48 KB
/
RootLeafSumPathFinder.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package org.sean.recursive;
import org.sean.tree.TreeNode;
import java.util.LinkedList;
import java.util.List;
/***
* 113. Path Sum II
*/
public class RootLeafSumPathFinder {
List<List<Integer>> result = new LinkedList<List<Integer>>();
LinkedList<Integer> path = new LinkedList<>();
private int sum;
private List<Integer> copy(List<Integer> path) {
List<Integer> list = new LinkedList<>();
list.addAll(path);
return list;
}
private boolean addNode(TreeNode root) {
if (root != null) {
path.add(root.val);
if (root.left == null && root.right == null) {
int total = 0;
int len = path.size();
for (int i = 0; i < len; i++) {
int digit = path.get(i);
total += digit;
}
if (total == sum) {
result.add(copy(path));
}
}
boolean leftAdded = addNode(root.left);
if (leftAdded) {
path.removeLast();
}
boolean rightAdded = addNode(root.right);
if (rightAdded) {
path.removeLast();
}
return true;
}
return false;
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if (root == null) {
return result;
}
this.sum = sum;
addNode(root);
return result;
}
}