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

For example, consider the following binary tree:

 
Root To Leaf Paths in Binary Tree

The binary tree has four root-to-leaf paths:
 
1 —> 2 —> 4
1 —> 2 —> 5
1 —> 3 —> 6 —> 8
1 —> 3 —> 7 —> 9

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 vector. If we encounter a leaf node, print all nodes present in the vector. Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

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

Java


Download  Run Code

Output:

[1, 2, 4]
[1, 2, 5]
[1, 3, 6, 8]
[1, 3, 7, 9]

Python


Download  Run Code

Output:

[1, 2, 4]
[1, 2, 5]
[1, 3, 6, 8]
[1, 3, 7, 9]

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.

 
The problem seems a bit difficult to solve without recursion. There is one workaround where we 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. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

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

Java


Download  Run Code

Output:

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

Python


Download  Run Code

Output:

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

Exercise:

1. Write an iterative solution to the above problem.

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