Given a binary tree, write a recursive algorithm to print all paths from every leaf node to root node in the binary tree.

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

The idea is to traverse the tree in a preorder fashion and store every encountered node in the current path from the root-to-leaf in a list. If we encounter a leaf node, print all nodes present in the list in reverse order.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

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

Java


Download  Run Code

Output:

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

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), where n is the total number of nodes in the binary tree. The program requires O(h) extra space for the call stack, where h is the height of the tree.

 
Exercise:

1. Write an iterative implementation of the above problem.

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