1022. Sum of Root To Leaf Binary Numbers

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int sum = 0;
public void construct(TreeNode root,String prev){
if (root == null) return;
if( root.left == null && root.right == null){
sum+=Integer.parseInt(prev+root.val,2);
return;
}
construct(root.left,prev+""+root.val);
construct(root.right,prev+""+root.val);
}
public int sumRootToLeaf(TreeNode root) {
if (root == null) return 0;
if(root.left == null && root.right == null) return root.val;
construct(root.left,root.val+"");
construct(root.right,root.val+"");
return sum;
}
}

### Like this:

Like Loading...

*Related*