# 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 9101112131415161718192021222324252627282930313233343536373839404142` `import java.util.*;import java.lang.*;import java.io.*;import java.math.*;//Definition for binary treeclass 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 = result.remainder(BigInteger.valueOf(1003)); return result.intValue(); } private void calculateSumRootToLeaf(TreeNode node, String currentSum, BigInteger[] result){ currentSum = currentSum + "" + node.val; if(node.left == null && node.right == null){ result = result.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); }}`