forked from alexkoby/Leetcode-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path129. Sum Root to Leaf Numbers
More file actions
36 lines (32 loc) · 884 Bytes
/
129. Sum Root to Leaf Numbers
File metadata and controls
36 lines (32 loc) · 884 Bytes
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int sumNumbers(TreeNode root) {
return sumNumbersHelp(root, 0);
}
public int sumNumbersHelp(TreeNode root, int currentSum){
if(root == null){
return 0;
}
int newSum = addNumberToSum(currentSum, root.val);
if(isLeaf(root)){
return newSum;
}
else{//Not a leaf
return sumNumbersHelp(root.left, newSum) + sumNumbersHelp(root.right, newSum);
}
}
public int addNumberToSum(int sum, int number){
return (sum * 10) + number;
}
public boolean isLeaf(TreeNode root){
return root.left == null && root.right == null;
}
}