Given a binary tree, write an iterative algorithm to print the leaf-to-root path for every leaf node. Use of recursion is prohibited.

For example, consider the following binary tree:

 
Print Leaf to Root Path

 
There are five leaf-to-root paths in the above binary tree:

4 —> 2 —> 1
5 —> 2 —> 1
8 —> 6 —> 3 —> 1
9 —> 6 —> 3 —> 1
7 —> 3 —> 1

Practice this problem

Since use of recursion is not allowed, we can do postorder iterative traversal of the tree and, while doing so, maintain a map that contains (child, parent) pair for every encountered node. Now, if a leaf node is encountered, we can easily print the leaf-to-root path using that map, as shown below in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
4 —> 2 —> 1
5 —> 2 —> 1
8 —> 6 —> 3 —> 1
9 —> 6 —> 3 —> 1
7 —> 3 —> 1

The time complexity of the above solution is O(n.log(n)), where n is the total number of nodes in the binary tree. The program requires O(n) extra space for the map. Unless we maintain a parent pointer in each tree node, the problem seems very difficult to solve without using any additional extra space apart from the stack.

 
One workaround doesn’t involve maintaining a parent pointer or the use of any additional extra space. We can store the path from the root-to-leaf in a string as we traverse the tree iteratively and print the path whenever we encounter any leaf node.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
4 —> 2 —> 1
5 —> 2 —> 1
8 —> 6 —> 3 —> 1
9 —> 6 —> 3 —> 1
7 —> 3 —> 1

 
Exercise:

1. Write a recursive implementation of the above problem.

2. Modify the solution to print the leaf-to-root path, having the sum of nodes equal to a given number.