-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path129. Sum Root to Leaf Numbers
39 lines (36 loc) · 1.12 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
/* RECURSION O(n), O(n) */
class Solution {
public int sumNumbers(TreeNode root){
ArrayList<String> list = new ArrayList<>();
solve(root, "", list);
int ans=0;
for(int i=0;i<list.size();i++){
ans+=Integer.parseInt(list.get(i));
}
return ans;
}
public static void solve(TreeNode root, String s, ArrayList<String> list){
if(root==null) return;
if(root.left==null && root.right==null){ //a leaf node
s+=root.val; //adding the leaf node
list.add(s);
return;
}
solve(root.left, s+ root.val, list);
solve(root.right, s+ root.val, list);
}
}
/* DFS O(n), O(1) */
class Solution {
int sum = 0;
public int sumNumbers(TreeNode root) {
solve(root, 0);
return sum;
}
public void solve(TreeNode root, int num){
num = num * 10 + root.val;
if (root.left != null) solve(root.left, num);
if (root.right != null) solve(root.right, num);
if (root.left == null && root.right == null) sum += num; //at leaf node we can make our sum
}
}