Given a binary tree, where each node stores a value between 0 and 9, calculate the sum of the numbers created by the paths from root to leaf.

For example,

Input: Binary Tree
     1
   /   \
  2     3
 / \
4   5
 
Output: 262
 
Explanation: Three root-to-leaf paths exist, and they are as follows:
 
[1 -> 2 -> 4]
[1 -> 2 -> 5]
[1 -> 3]
 
They represent the numbers 124, 125, and 13, respectively. They add up to 124 + 123 + 13 to make 262.

1. Recursive Solution

We can use recursion to solve the problem. The idea is to traverse the tree in a preorder fashion and construct the sum for each root-to-leaf path, as we go from top to bottom. Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

262

Java


Download  Run Code

Output:

262

Python


Download  Run Code

Output:

262

The above recursive answer has an O(n) time complexity, where n is the total number of nodes in the binary tree. The program needs O(h) auxiliary space for the call stack, where ‘h’ is the height of the tree.

2. Iterative Solution

In an iterative version, we can traverse the tree in level order, and while doing so, we update the data of every encountered node with the sum of the paths so far. Now, if a leaf node is encountered, we can easily add the root-to-leaf path sum to the result, as demonstrated below in C++, Java, and Python. Keep in mind that this solution changes the binary tree nodes’ values. This can be avoided by making a copy of the child nodes and enqueuing them after updating their data.

C++


Download  Run Code

Output:

262

Java


Download  Run Code

Output:

262

Python


Download  Run Code

Output:

262

The above iterative method has O(n) time complexity, where n is the total number of nodes in the binary tree. The program needs O(n) auxiliary space for the queue data structure.