/
Solution.java
executable file
·47 lines (40 loc) · 1.11 KB
/
Solution.java
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int helper(TreeNode root, int pre){
if(root == null) return 0;
pre = pre * 10 + root.val;
if(root.left == null && root.right == null) return pre;
return helper(root.left, pre) + helper(root.right, pre);
}
public int sumNumbers(TreeNode root) {
return helper(root, 0);
}
}
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int sumNumbers(TreeNode root, int parentval){
if(root == null) return 0;
int p = parentval * 10 + root.val;
if(root.left == null && root.right == null) return p;
return sumNumbers(root.left, p) + sumNumbers(root.right, p);
}
public int sumNumbers(TreeNode root) {
return sumNumbers(root, 0);
}
}