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

11 thoughts on “LeetCode – Sum Root to Leaf Numbers (Java)”

  1. I might have a simpler approach – without passing the sum – just the number we built so far.


    int sumRootToLeaf(Node root)
    {
    if (root == null) return 0;

    return sumRootToLeaf(root, 0)
    }

    int sumNodeToLeaf(Node node, int num)
    {
    num = num * 10 + node.val;

    // Leaf
    if (node.left == null && node.right == null)
    {
    return num;
    }

    int sum = 0;

    if (node.left != null)
    {
    sum += sumNodeToLeaf(node.left, num);
    }

    if (node.right != null)
    {
    sum += sumNodeToLeaf(node.right, num);
    }

    return sum;
    }

  2. Your code has bug, instead of using:

    int currValue = Integer.valueOf(sb.toString());

    You should use:

    int currValue = Integer.parseInt(sb.toString(), 2);

  3. You don’t need extra space

    /**
    * Definition for a binary tree node.
    * public class TreeNode {
    * int val;
    * TreeNode left;
    * TreeNode right;
    * TreeNode(int x) { val = x; }
    * }
    */
    import java.lang.Integer;

    class Solution {
    public int sumNumbers(TreeNode root) {

    if (root == null) return 0;

    return sumNumbers(0, “”, root);
    }

    public int sumNumbers(int sum, String path, TreeNode root) {

    if (root.left == null && root.right == null) {
    return sum += Integer.parseInt(path + root.val);
    }

    if (root.left != null) {
    sum = sumNumbers(sum, path + root.val , root.left);
    }

    if (root.right != null) {
    sum = sumNumbers(sum, path + root.val , root.right);
    }

    return sum;
    }
    }

  4. My version of this:

    public static int temp_sum= 0;
    public static void dfs(TreeNode root, int sum){
    if (root == null) return ;

    if (root.left != null)
    sum += root.data*10 + root.left.data;

    if(root.right != null)
    sum += root.data*10 + root.right.data;

    if (sum > temp_sum) //only keep max sum during back track of call functions
    temp_sum = sum;

    dfs(root.left,sum);
    dfs(root.right, sum);
    }

  5. Why do we need to have num and sum as parameters? this code below should just work:

    int sumTree(TreeNode* node, int curSum)
    {
    if(!node)
    return 0;

    curSum = (curSum * 10) + node->val;
    if(isLeafNode(node))
    return curSum;

    return sumTree(node->left, curSum) + sumTree(node->right, curSum);

    }

  6. 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;

    }

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

    }

    }

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

  9. 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]

Leave a Comment