LeetCode – Sum Root to Leaf Numbers (Java)

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3

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 = 25.

Java Solution - Recursive

This problem can be solved by a typical DFS approach.

public int sumNumbers(TreeNode root) {
    int result = 0;
    if(root==null)
        return result;
 
    ArrayList<ArrayList<TreeNode>> all = new ArrayList<ArrayList<TreeNode>>();
    ArrayList<TreeNode> l = new ArrayList<TreeNode>();
    l.add(root);
    dfs(root, l, all);
 
    for(ArrayList<TreeNode> a: all){
        StringBuilder sb = new StringBuilder();
        for(TreeNode n: a){
            sb.append(String.valueOf(n.val));
        }
        int currValue = Integer.valueOf(sb.toString());
        result = result + currValue;
    }
 
    return result;
}
 
public void dfs(TreeNode n, ArrayList<TreeNode> l,  ArrayList<ArrayList<TreeNode>> all){
    if(n.left==null && n.right==null){
        ArrayList<TreeNode> t = new ArrayList<TreeNode>();
        t.addAll(l);
        all.add(t);
    }
 
    if(n.left!=null){
        l.add(n.left);
        dfs(n.left, l, all);
        l.remove(l.size()-1);
    }
 
    if(n.right!=null){
        l.add(n.right);
        dfs(n.right, l, all);
        l.remove(l.size()-1);
    }
 
}

Same approach, but simpler coding style.

public int sumNumbers(TreeNode root) {
    if(root == null) 
        return 0;
 
    return dfs(root, 0, 0);
}
 
public int dfs(TreeNode node, int num, int sum){
    if(node == null) return sum;
 
    num = num*10 + node.val;
 
    // leaf
    if(node.left == null && node.right == null) {
        sum += num;
        return sum;
    }
 
    // left subtree + right subtree
    sum = dfs(node.left, num, sum) + dfs(node.right, num, sum);
    return sum;
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Juan Carlos Nuño

    Better BFS solution, using only one queue:


    public int sumNumbers(TreeNode root) {
    if (root == null) return 0;

    int sum = 0;
    Queue q = new LinkedList();
    q.offer(root);

    while (!q.isEmpty()) {
    TreeNode temp = q.poll();

    if (temp.left == null && temp.right == null)
    sum += temp.val;

    int num = (temp.val * 10);

    if (temp.left != null) {
    temp.left.val = temp.left.val + num;
    q.offer (temp.left);
    }

    if (temp.right != null) {
    temp.right.val = temp.right.val + num;
    q.offer(temp.right);
    }

    }

    return sum;

    }

  • Madhumitha

    Post order travesal+addition logics

    import java.util.Stack;

    public class sumToLeaf {

    public static void main(String[] args) {

    TreeNode t = new TreeNode(1);

    t.left = new TreeNode(2);

    t.right = new TreeNode(3);

    t.left.left = new TreeNode(4);

    t.left.right = new TreeNode(5);

    t.left.right.left = new TreeNode(6);

    int s=sum2Leaf(t);

    System.out.println(s);

    }

    private static int sum2Leaf(TreeNode root)

    {

    Stack stack = new Stack();

    stack.push(root);

    TreeNode prev = null;

    int num=root.val,sum=0;

    int temp=0;

    while(!stack.empty()){

    TreeNode curr = stack.peek();

    if(prev == null || prev.left == curr || prev.right == curr)

    {

    if(curr.left != null)

    {

    num=(num*10)+curr.left.val;

    stack.push(curr.left);

    }

    else if(curr.right != null)

    {

    sum+=num;

    temp=stack.peek().val;

    num=num-temp+curr.right.val;

    stack.push(curr.right);

    }

    else

    {

    sum+=num;

    temp= stack.pop().val;

    num=num-temp;

    }

    }

    else if(curr.left == prev)

    {

    if(curr.right != null)

    {

    num=num+curr.right.val;

    stack.push(curr.right);

    }else

    {

    temp= stack.pop().val;

    num=(num-(temp*10))/10;

    }

    }

    else if(curr.right == prev)

    {

    temp= stack.pop().val;

    num=(num-(temp*10))/10;

    }

    prev = curr;

    }

    return sum;

    }

    }

  • disqus_t359ByPNg8

    Solution using BFS !

    An Iterative Solution !

    public int sumNumbers(TreeNode root) {

    if(root == null){
    return 0;

    }
    int sum =0;
    LinkedList queue = new LinkedList();
    LinkedList sumQueue = new LinkedList();

    queue.add(root);
    sumQueue.add(root.val);
    while(queue.isEmpty() == false){

    TreeNode temp = queue.poll();
    int tempSum = sumQueue.poll();

    if(temp.left == null && temp.right == null){
    sum = sum + tempSum;
    }

    if(temp.left!=null){

    queue.add(temp.left);
    sumQueue.add(tempSum*10+ temp.left.val);

    }

    if(temp.right != null){
    queue.add(temp.right);
    sumQueue.add(tempSum *10 + temp.right.val);

    }

    }

    return sum;
    }

  • Karim El Shabrawy

    Hi,

    I think I get a better solution :

    public int sumNumbers(TreeNode root) {

    return sumNumbers(root, 0);
    }

    public int sumNumbers(TreeNode root, int current) {

    if (root == null) return 0;
    if (root.left == null && root.right == null) return root.val+current*10;

    current = current*10 + root.val;

    return sumNumbers(root.left, current)+sumNumbers(root.right, current);

    }


    What do you think ?

    BR,

    Karim El Shabrawy
    [email protected]