VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-root-leaf-path-without-using-recursion/

⇱ Print root to leaf paths without using recursion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print root to leaf paths without using recursion

Last Updated : 23 Jul, 2025

Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the leaf nodes of the binary tree.

Example:

Input:

👁 ex-3

Output:
1 2 4
1 2 5
1 3

[Expected Approach - 1] Using Parent HashMap - O(n) Time and O(n) Space

The idea is to use a preorder traversal technique using a stack, and maintain hashmap to keep track of each node's parent, When we reach at leaf node, print path from root to that lead node using parent map.

Follow the steps below to solve the problem:

  • Push the root node onto the stack and Store the root's parent as null in the parent map.
  • While the stack is not empty, pop the top node
    • If the node is a leaf node then Trace the path from the leaf node to the root using the parent map and print the path.
    • If the node has a right child, push it onto the stack and store its parent in the map.
    • If the node has a left child, push it onto the stack and store its parent in the map.

Below is the implementation of this idea.


Output
10 8 3 
10 8 5 
10 2 2 

Note : We can optimize this approach. We do not need to maintain parent map. Below there is another approach by we can print all path from root to leaf without using parent array.

[Expected Approach - 2] Using Stack - O(n) Time and O(n) Space

The idea is to use stack to store pairs of nodes and their respective paths from the root, starting with the root node and its value, traverse iteratively by processing each node by popping it from the stack. if the node is a leaf, its path is added to the result. else if the node has children, the right and left children are pushed onto the stack along with their updated paths.

Follow the steps below to solve the problem:

  • Initialize stack, that stores pairs of nodes and the path from the root to that node.
  • Push the root node and its path (starting with just the root’s value) onto the stack.
  • While the stack isn't empty, pop a pair of node and its path from the stack.
    • If the current node is a leaf, add its path to the result.
    • If the current node has a right child, push the right child and its updated path onto the stack.
    • If the current node has a left child, push the left child and its updated path onto the stack.
  • return result which represents all the paths from root-to-leaf.

Below is the implementation of the above approach: 


Output
10 8 3 
10 8 5 
10 2 2 

Related article:

Comment
Article Tags:
Article Tags: