Java Program For Sum Root to Leaf Numbers

Sum Root to Leaf Numbers is a popular interview problem which is asked in companies like Google & Microsoft. You can find this question in LeetCode & InterviewBit.

We have been given a binary tree where each node can contain any number between 0-9.

    2
   / \
  4   8

For the above tree, there are two root to leaf paths, 2->4 = 24 & 2->8 = 28. So result should be 24 + 28 =  52. In InterviewBit problem, we need to get the remainder after dividing the result by 1003 (result % 1003) to restrict number overflow. Number overflow can happen if tree has a lot of depth.

Below you can find the working Java solution for this problem. It will do a pre-order traversal & do a backtracking to find all possible solutions & add them to result. Time complexity is O(n) as we need to traverse the full tree once. Space complexity is constant O(1) if we don't consider recursion stack.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;

//Definition for binary tree
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) {
        val = x;
        left=null;
        right=null;
    }
}

class Solution {
    public int sumNumbers(TreeNode A) {
        String currentSum = "";
        //Like Integer, BigInteger object is also immutable. Assigning new object refrence
        //inside method won't change method argument. So using an array of BigInteger.
        BigInteger[] result = new BigInteger[]{BigInteger.valueOf(0)};
        calculateSumRootToLeaf(A, currentSum, result);
        result[0] = result[0].remainder(BigInteger.valueOf(1003));
        return result[0].intValue();
    }
    private void calculateSumRootToLeaf(TreeNode node, String currentSum, BigInteger[] result){
        currentSum = currentSum + "" + node.val;
        if(node.left == null && node.right == null){
            result[0] = result[0].add(new BigInteger(currentSum));
        } else {
            if(node.left != null){
                calculateSumRootToLeaf(node.left, currentSum, result);
            }
            if(node.right != null){
                calculateSumRootToLeaf(node.right, currentSum, result);
            }
        }
        currentSum = currentSum.substring(0, currentSum.length() - 1);
    }
}

Comments