-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path129. Sum Root to Leaf Numbers
57 lines (51 loc) · 1.38 KB
/
129. Sum Root to Leaf Numbers
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
//O(n) time and space
class Solution {
int sum = 0;
public int sumNumbers(TreeNode root) {
if(root==null) return 0;
dfs(root, 0);
return sum;
}
public void dfs(TreeNode root, int cur) {
if(root==null) return;
cur = cur*10 + root.val;
if(root.left==null && root.right==null) {
sum+=cur;
}
else {
dfs(root.left, cur);
dfs(root.right, cur);
}
cur-=root.val;
cur/=10;
}
}
//O(n^2) time and O(n) space
class Solution {
public int sumNumbers(TreeNode root) {
List<List<Integer>> result = new ArrayList();
List<Integer> list = new ArrayList();
backtrack(result, list, root);
int sum = 0;
for(List<Integer> r:result) {
String s = "";
for(Integer l:r) {
s+=l;
}
sum+=Integer.parseInt(s);
}
return sum;
}
public void backtrack(List<List<Integer>> result, List<Integer> list, TreeNode root) {
if(root==null) return;
list.add(root.val);
if(root.left==null && root.right==null) {
result.add(new ArrayList(list));
}
else {
backtrack(result, list, root.left);
backtrack(result, list, root.right);
}
list.remove(list.size()-1);
}
}