Given a binary tree containing digits from
0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path
1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path
The root-to-leaf path
1->2 represents the number 12.The root-to-leaf path
1->3 represents the number 13.
Return the sum = 12 + 13 =
Solution:
For each node, find its path number and path related depth, then we can get the sum of that node.
For the example mentioned above:
sum(root) = 1 * pow(10, 1) + 1 * pow(10, 1) = 20
sum(root.left) = 2 * pow(10, 0) = 2
sum(root.right) = 3 * pow(10, 0) = 3
25.Solution:
For each node, find its path number and path related depth, then we can get the sum of that node.
For the example mentioned above:
sum(root) = 1 * pow(10, 1) + 1 * pow(10, 1) = 20
sum(root.left) = 2 * pow(10, 0) = 2
sum(root.right) = 3 * pow(10, 0) = 3
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// calcalate value for each non-zero element by finding all its depths. like for 1: (1+1) * Math.pow(1) = 20;
public class Solution {
public int sumNumbers(TreeNode root) {
if(root == null) return 0;
ArrayList sumArray = new ArrayList();
traverse(root, sumArray);
int sum = 0;
for(int i : sumArray) sum+= i;
return sum;
}
public void traverse(TreeNode root, ArrayList sumArray){
if(root.val != 0){
int sum = 0;
ArrayList result = new ArrayList();
findDepth(root, result, 0);
for(int i : result) sum += root.val * Math.pow(10, i);
sumArray.add(sum);
}
if(root.left != null) traverse(root.left, sumArray);
if(root.right != null) traverse(root.right, sumArray);
}
public void findDepth(TreeNode root, ArrayList result, int depth){
if(root.left == null && root.right == null){
result.add(depth);
return;
}
if(root.left != null) findDepth(root.left, result, depth+1);
if(root.right != null) findDepth(root.right, result, depth+1);
}
}
No comments:
Post a Comment