1022. Sum of Root To Leaf Binary Numbers

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;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s