-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution129.java
50 lines (39 loc) · 1.24 KB
/
Solution129.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
package leetcode.tree.preorder;
import leetcode.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Solution129 {
public static void main(String[] args) {
TreeNode node = new TreeNode(1);
node.left = new TreeNode(2);
node.right = new TreeNode(3);
new Solution129().sumNumbers(node);
}
List<LinkedList<Integer>> all;
public int sumNumbers(TreeNode root) {
all = new ArrayList<>();
doSumNumbers(root, new LinkedList<>());
int res = 0;
for (LinkedList<Integer> list : all) {
StringBuilder builder = new StringBuilder();
for (Integer i : list) {
builder.append(i);
}
res += Integer.parseInt(builder.toString());
}
return res;
}
private void doSumNumbers(TreeNode node, LinkedList<Integer> element) {
if (node == null) {
return;
}
element.addLast(node.val);
if (node.left == null && node.right == null) {
all.add((LinkedList<Integer>) element.clone());
}
doSumNumbers(node.left, element);
doSumNumbers(node.right, element);
element.removeLast();
}
}