Skip to content

Commit 2325bce

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 129_Sum_Root_to_Leaf_Numbers.java
1 parent 2ab9169 commit 2325bce

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public int sumNumbers(TreeNode root) {
3+
if (root == null) {
4+
return 0;
5+
}
6+
return dfs(root, 0);
7+
}
8+
9+
private int dfs(TreeNode root, int levelBase) {
10+
if (root == null) {
11+
return 0;
12+
}
13+
14+
if (root.left == null && root.right == null) {
15+
return levelBase + root.val;
16+
}
17+
18+
int nextLevelBase = 10 * (levelBase + root.val);
19+
int left = dfs(root.left, nextLevelBase);
20+
int right = dfs(root.right, nextLevelBase);
21+
22+
return left + right;
23+
}
24+
}

0 commit comments

Comments
 (0)