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:
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.
C++
// C++ program to Print root to leaf path without
// using recursion
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Function to print root to leaf path for a leaf
// using parent nodes stored in map
void printTopToBottomPath(Node* curr,
unordered_map<Node*, Node*>& parent) {
stack<Node*> stk;
// start from leaf node and keep on pushing
// nodes into stack till root node is reached
while (curr) {
stk.push(curr);
curr = parent[curr];
}
// Start popping nodes from stack and print them
while (!stk.empty()) {
curr = stk.top();
stk.pop();
cout << curr->data << " ";
}
cout << endl;
}
// An iterative function to do preorder traversal
// of binary tree and print root to leaf path
// without using recursion
void printRootToLeaf(Node* root) {
if (root == nullptr)
return;
// Create an empty stack and push root
// to it
stack<Node*> nodeStack;
nodeStack.push(root);
// Create a map to store parent pointers
// of binary tree nodes
unordered_map<Node*, Node*> parent;
// parent of root is NULL
parent[root] = nullptr;
while (!nodeStack.empty()) {
// Pop the top item from stack
Node* current = nodeStack.top();
nodeStack.pop();
// If leaf node encountered, print Top To
// Bottom path
if (!(current->left) && !(current->right)){
printTopToBottomPath(current, parent);
}
// Push right & left children of the popped node
// to stack. Also set their parent pointer in
// the map
// Note that right child is pushed first so that
// left is processed first
if (current->right) {
parent[current->right] = current;
nodeStack.push(current->right);
}
if (current->left) {
parent[current->left] = current;
nodeStack.push(current->left);
}
}
}
int main() {
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
Node* root = new Node(10);
root->left = new Node(8);
root->right = new Node(2);
root->left->left = new Node(3);
root->left->right = new Node(5);
root->right->left = new Node(2);
printRootToLeaf(root);
return 0;
}
Java
// Java program to Print root to leaf path without
// using recursion
import java.util.*;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to print root to leaf path for a leaf
// using parent nodes stored in map
static void printTopToBottomPath(Node curr, Map<Node, Node> parent) {
Stack<Node> stk = new Stack<>();
// start from leaf node and keep on pushing
// nodes into stack till root node is reached
while (curr != null) {
stk.push(curr);
curr = parent.get(curr);
}
// Start popping nodes from stack and print them
while (!stk.isEmpty()) {
curr = stk.pop();
System.out.print(curr.data + " ");
}
System.out.println();
}
// An iterative function to do preorder traversal
// of binary tree and print root to leaf path
// without using recursion
static void printRootToLeaf(Node root) {
if (root == null)
return;
// Create an empty stack and push root to it
Stack<Node> nodeStack = new Stack<>();
nodeStack.push(root);
// Create a map to store parent pointers of binary
// tree nodes
Map<Node, Node> parent = new HashMap<>();
// parent of root is NULL
parent.put(root, null);
while (!nodeStack.isEmpty()) {
// Pop the top item from stack
Node current = nodeStack.pop();
// If leaf node encountered, print Top To
// Bottom path
if (current.left == null && current.right == null) {
printTopToBottomPath(current, parent);
}
// Push right & left children of the popped node
// to stack. Also set their parent pointer in
// the map
// Note that right child is pushed first so that
// left is processed first
if (current.right != null) {
parent.put(current.right, current);
nodeStack.push(current.right);
}
if (current.left != null) {
parent.put(current.left, current);
nodeStack.push(current.left);
}
}
}
public static void main(String[] args) {
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
Node root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
printRootToLeaf(root);
}
}
Python
# Python program to Print root to leaf path without
# using recursion
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to print root to leaf path for a leaf
# using parent nodes stored in map
def printTopToBottomPath(curr, parent):
stk = []
# start from leaf node and keep on pushing
# nodes into stack till root node is reached
while curr:
stk.append(curr)
curr = parent[curr]
# Start popping nodes from stack and print them
while stk:
curr = stk.pop()
print(curr.data, end=" ")
print()
# An iterative function to do preorder traversal
# of binary tree and print root to leaf path
# without using recursion
def printRootToLeaf(root):
if root is None:
return
# Create an empty stack and push root to it
nodeStack = []
nodeStack.append(root)
# Create a dictionary to store parent pointers
# of binary tree nodes
parent = {}
# parent of root is None
parent[root] = None
while nodeStack:
# Pop the top item from stack
current = nodeStack.pop()
# If leaf node encountered, print Top To
# Bottom path
if not current.left and not current.right:
printTopToBottomPath(current, parent)
# Push right & left children of the popped node
# to stack. Also set their parent pointer in
# the dictionary
# Note that right child is pushed first so that
# left is processed first
if current.right:
parent[current.right] = current
nodeStack.append(current.right)
if current.left:
parent[current.left] = current
nodeStack.append(current.left)
# Constructed binary tree is
# 10
# / \
# 8 2
# / \ /
# 3 5 2
root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(5)
root.right.left = Node(2)
printRootToLeaf(root)
C#
// C# program to Print root to leaf path without
// using recursion
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to print root to leaf path for a leaf
// using parent nodes stored in map
static void printTopToBottomPath(Node curr,
Dictionary<Node, Node> parent) {
Stack<Node> stk = new Stack<Node>();
// start from leaf node and keep on pushing
// nodes into stack till root node is reached
while (curr != null) {
stk.Push(curr);
curr = parent[curr];
}
// Start popping nodes from stack and print them
while (stk.Count > 0) {
curr = stk.Pop();
Console.Write(curr.data + " ");
}
Console.WriteLine();
}
// An iterative function to do preorder traversal
// of binary tree and print root to leaf path
// without using recursion
static void printRootToLeaf(Node root) {
if (root == null)
return;
// Create an empty stack and push root to it
Stack<Node> nodeStack = new Stack<Node>();
nodeStack.Push(root);
// Create a map to store parent pointers of binary
// tree nodes
Dictionary<Node, Node> parent = new Dictionary<Node, Node>();
// parent of root is NULL
parent[root] = null;
while (nodeStack.Count > 0) {
// Pop the top item from stack
Node current = nodeStack.Pop();
// If leaf node encountered, print Top To
// Bottom path
if (current.left == null && current.right == null) {
printTopToBottomPath(current, parent);
}
// Push right & left children of the popped node
// to stack. Also set their parent pointer in
// the map
// Note that right child is pushed first so that
// left is processed first
if (current.right != null) {
parent[current.right] = current;
nodeStack.Push(current.right);
}
if (current.left != null) {
parent[current.left] = current;
nodeStack.Push(current.left);
}
}
}
static void Main() {
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
Node root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
printRootToLeaf(root);
}
}
JavaScript
// Javascript program to Print root to leaf path without
// using recursion
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// Function to print root to leaf path for a leaf
// using parent nodes stored in map
function printTopToBottomPath(curr, parent) {
let stk = [];
// start from leaf node and keep on pushing
// nodes into stack till root node is reached
while (curr) {
stk.push(curr);
curr = parent.get(curr);
}
// Start popping nodes from stack and print them
while (stk.length > 0) {
curr = stk.pop();
process.stdout.write(curr.data + " ");
}
console.log();
}
// An iterative function to do preorder traversal
// of binary tree and print root to leaf path
// without using recursion
function printRootToLeaf(root) {
if (root === null) return;
// Create an empty stack and push root to it
let nodeStack = [];
nodeStack.push(root);
// Create a map to store parent pointers of binary
// tree nodes
let parent = new Map();
// parent of root is NULL
parent.set(root, null);
while (nodeStack.length > 0) {
// Pop the top item from stack
let current = nodeStack.pop();
// If leaf node encountered, print Top To
// Bottom path
if (!current.left && !current.right) {
printTopToBottomPath(current, parent);
}
// Push right & left children of the popped node
// to stack. Also set their parent pointer in
// the map
// Note that right child is pushed first so that
// left is processed first
if (current.right) {
parent.set(current.right, current);
nodeStack.push(current.right);
}
if (current.left) {
parent.set(current.left, current);
nodeStack.push(current.left);
}
}
}
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
let root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
printRootToLeaf(root);
Output10 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:
C++
// C++ code of print all paths from root node
// to leaf node using stack
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Function to get all paths from root
// to leaf nodes using a stack
vector<vector<int>> Paths(Node* root) {
vector<vector<int>> result;
if (!root) return result;
// Stack to store pairs of nodes and the
// path from the root to that node
stack<pair<Node*, vector<int>>> stk;
stk.push({root, {root->data}});
while (!stk.empty()) {
// Get the current node and its
// associated path from the stack
auto curr = stk.top();
stk.pop();
Node* currNode = curr.first;
vector<int> path = curr.second;
// If the current node is a leaf node,
// add its path to the result
if (!currNode->left && !currNode->right) {
result.push_back(path);
}
// If the current node has a right child,
// push it to the stack with its path
if (currNode->right) {
vector<int> rightPath = path;
rightPath.push_back(currNode->right->data);
stk.push({currNode->right, rightPath});
}
// If the current node has a left child,
// push it to the stack with its path
if (currNode->left) {
vector<int> leftPath = path;
leftPath.push_back(currNode->left->data);
stk.push({currNode->left, leftPath});
}
}
return result;
}
int main() {
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
Node* root = new Node(10);
root->left = new Node(8);
root->right = new Node(2);
root->left->left = new Node(3);
root->left->right = new Node(5);
root->right->left = new Node(2);
vector<vector<int>> paths = Paths(root);
for (const auto& path : paths) {
for (int nodeValue : path) {
cout << nodeValue << " ";
}
cout << endl;
}
return 0;
}
Java
// Java code of print all paths from root node
// to leaf node using stack
import java.util.*;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class Pair {
Node node;
List<Integer> path;
public Pair(Node node, List<Integer> path) {
this.node = node;
this.path = path;
}
}
class GfG {
// Function to get all paths from root
// to leaf nodes using a stack
static List<List<Integer>> Paths(Node root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
// Stack to store pairs of nodes and the
// path from the root to that node
Stack<Pair> stk = new Stack<>();
// Create an ArrayList with the root node's data
List<Integer> rootPath = new ArrayList<>();
rootPath.add(root.data);
stk.push(new Pair(root, rootPath));
while (!stk.isEmpty()) {
// Get the current node and its
// associated path from the stack
Pair curr = stk.pop();
Node currNode = curr.node;
List<Integer> path = curr.path;
// If the current node is a leaf node,
// add its path to the result
if (currNode.left == null && currNode.right == null) {
result.add(path);
}
// If the current node has a right child,
// push it to the stack with its path
if (currNode.right != null) {
List<Integer> rightPath = new ArrayList<>(path);
rightPath.add(currNode.right.data);
stk.push(new Pair(currNode.right, rightPath));
}
// If the current node has a left child,
// push it to the stack with its path
if (currNode.left != null) {
List<Integer> leftPath = new ArrayList<>(path);
leftPath.add(currNode.left.data);
stk.push(new Pair(currNode.left, leftPath));
}
}
return result;
}
public static void main(String[] args) {
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
Node root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
List<List<Integer>> paths = Paths(root);
for (List<Integer> path : paths) {
for (int nodeValue : path) {
System.out.print(nodeValue + " ");
}
System.out.println();
}
}
}
Python
# Python code to print all paths from
# root node to leaf node using stack.
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Function to get all paths from root
# to leaf nodes using a stack
def Paths(root):
result = []
if not root:
return result
# Stack to store pairs of nodes and the
# path from the root to that node
stk = [(root, [root.data])]
while stk:
# Get the current node and its
# associated path from the stack
currNode, path = stk.pop()
# If the current node is a leaf node,
# add its path to the result
if not currNode.left and not currNode.right:
result.append(path)
# If the current node has a right child,
# push it to the stack with its path
if currNode.right:
rightPath = path + [currNode.right.data]
stk.append((currNode.right, rightPath))
# If the current node has a left child,
# push it to the stack with its path
if currNode.left:
leftPath = path + [currNode.left.data]
stk.append((currNode.left, leftPath))
return result
if __name__ == "__main__":
# Constructed binary tree is
# 10
# / \
# 8 2
# / \ /
# 3 5 2
root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(5)
root.right.left = Node(2)
paths = Paths(root)
for path in paths:
print(" ".join(map(str, path)))
C#
// C# code to print all paths from root
// node to leaf node using stack.
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to get all paths from root
// to leaf nodes using a stack
static List<List<int>> Paths(Node root) {
List<List<int>> result = new List<List<int>>();
if (root == null) return result;
// Stack to store pairs of nodes and the
// path from the root to that node
Stack<Tuple<Node, List<int>>> stk =
new Stack<Tuple<Node, List<int>>>();
stk.Push(Tuple.Create(root,
new List<int> { root.data }));
while (stk.Count > 0) {
// Get the current node and its
// associated path from the stack
var curr = stk.Pop();
Node currNode = curr.Item1;
List<int> path = curr.Item2;
// If the current node is a leaf node,
// add its path to the result
if (currNode.left == null && currNode.right == null) {
result.Add(path);
}
// If the current node has a right child,
// push it to the stack with its path
if (currNode.right != null) {
List<int> rightPath = new List<int>(path);
rightPath.Add(currNode.right.data);
stk.Push(Tuple.Create(currNode.right, rightPath));
}
// If the current node has a left child,
// push it to the stack with its path
if (currNode.left != null) {
List<int> leftPath = new List<int>(path);
leftPath.Add(currNode.left.data);
stk.Push(Tuple.Create(currNode.left, leftPath));
}
}
return result;
}
static void Main() {
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
Node root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
List<List<int>> paths = Paths(root);
foreach (var path in paths) {
Console.WriteLine(string.Join(" ", path));
}
}
}
JavaScript
// JavaScript code to print all paths from
// root node to leaf node using stack.
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Function to get all paths from root
// to leaf nodes using a stack
function Paths(root) {
const result = [];
if (!root) return result;
// Stack to store pairs of nodes and the
// path from the root to that node
const stk = [[root, [root.data]]];
while (stk.length > 0) {
// Get the current node and its
// associated path from the stack
const [currNode, path] = stk.pop();
// If the current node is a leaf node,
// add its path to the result
if (!currNode.left && !currNode.right) {
result.push(path);
}
// If the current node has a right child,
// push it to the stack with its path
if (currNode.right) {
const rightPath = [...path, currNode.right.data];
stk.push([currNode.right, rightPath]);
}
// If the current node has a left child,
// push it to the stack with its path
if (currNode.left) {
const leftPath = [...path, currNode.left.data];
stk.push([currNode.left, leftPath]);
}
}
return result;
}
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
const root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
const allPaths = Paths(root);
allPaths.forEach(path => {
console.log(path.join(' '));
});
Output10 8 3
10 8 5
10 2 2
Related article:
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem