Skip to content

Commit 96e2c57

Browse files
authored
Tree sum-root-to-leaf-numbers java (#22)
1 parent 0daca30 commit 96e2c57

File tree

2 files changed

+126
-83
lines changed

2 files changed

+126
-83
lines changed

Java/sum-root-to-leaf-numbers.java

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*
16+
* Runtime: 0 ms
17+
Memory Usage: 39.2 MB
18+
*/
19+
20+
class Solution {
21+
int sum = 0;
22+
23+
public int sumNumbers(TreeNode root) {
24+
traverse(root, 0);
25+
return sum;
26+
}
27+
28+
public void traverse(TreeNode root, int n) {
29+
// if the node is null, return from the function (specially to handle if root of
30+
// tree is null)
31+
if (root == null)
32+
return;
33+
// shift the previous units place digit to ten's place by multiplying it by 10
34+
// and add the current value of node
35+
n = n * 10 + root.val;
36+
// if the node does not have a left or right children is null,
37+
// the current node is leaf node, so add the value to sum and return
38+
if (root.left == null && root.right == null) {
39+
sum += n;
40+
return;
41+
}
42+
// recurse for left subtree
43+
traverse(root.left, n);
44+
// recurse for right subtree
45+
traverse(root.right, n);
46+
}
47+
}

0 commit comments

Comments
 (0)