Inorder Tree Traversal without Recursion
Given a binary tree, the task is to perform in-order traversal of the tree without using recursion.
Example:
Input:
Output: 4 2 5 1 3
Explanation: Inorder traversal (Left->Root->Right) of the tree is 4 2 5 1 3Input:
Output: 1 7 10 8 6 10 5 6
Explanation: Inorder traversal (Left->Root->Right) of the tree is 1 7 10 8 6 10 5 6
Table of Content
[Naive Approach] Using Stack - O(n) Time and O(h) Space
The idea is to implement recursion using a stack to perform in-order traversal. Starting from root node, keep on pushing the node into a stack and move to left node. When node becomes null, pop a node from the stack, print its value and move to the right node.
Illustration:
Let us consider the below tree for example:
Initially Creates an empty stack: S = NULL and set current as address of root: current -> 1
- Starting at Root (Node 1): current = 1
- Push 1 to the stack. Stack S = [1]
- Move current to the left child: current = 2
- At Node 2:
- Push 2 to the stack. Stack S = [2, 1]
- Move current to the left child: current = 4
- At Node 4:
- Push 4 to the stack. Stack S = [4, 2, 1]
- Move current to the left child: current = NULL (Node 4 has no left child)
- current is NULL:
- Pop 4 from the stack. Stack S = [2, 1]
- Print 4
- Move current to the right child of Node 4: current = NULL (Node 4 has no right child)
- Repeat with current = NULL:
- Pop 2 from the stack. Stack S = [1]
- Print 2
- Move current to the right child of Node 2: current = 5
- At Node 5:
- Push 5 to the stack. Stack S = [5, 1]
- Move current to the left child: current = NULL (Node 5 has no left child)
- current is NULL:
- Pop 5 from the stack. Stack S = [1]
- Print 5
- Move current to the right child of Node 5: current = NULL (Node 5 has no right child)
- Repeat with current = NULL:
- Pop 1 from the stack. Stack S = []
- Print 1
- Move current to the right child of Node 1: current = 3
- At Node 3:
- Push 3 to the stack. Stack S = [3]
- Move current to the left child: current = NULL (Node 3 has no left child)
- current is NULL:
- Pop 3 from the stack. Stack S = []
- Print 3
- Move current to the right child of Node 3: current = NULL (Node 3 has no right child)
// C++ program to print inorder traversal
// using stack.
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
//Iterative function for inorder tree traversal
vector<int> inOrder(Node* root) {
vector<int> ans;
stack<Node*> s;
Node* curr = root;
while (curr != nullptr || s.empty() == false) {
// Reach the left most Node of the
// curr Node
while (curr != nullptr) {
// Place pointer to a tree node on
// the stack before traversing
// the node's left subtree
s.push(curr);
curr = curr->left;
}
// Current must be NULL at this point
curr = s.top();
s.pop();
ans.push_back(curr->data);
// we have visited the node and its
// left subtree. Now, it's right
// subtree's turn
curr = curr->right;
}
return ans;
}
int main() {
// Constructed binary tree is
// 1
// / \
// 2 3
// / \
// 4 5
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
vector<int> res = inOrder(root);
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
}
// Java program to print inorder traversal
// using stack.
import java.util.ArrayList;
import java.util.Stack;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Iterative function for inorder tree traversal
static ArrayList<Integer> inOrder(Node root) {
ArrayList<Integer> ans = new ArrayList<>();
Stack<Node> s = new Stack<>();
Node curr = root;
while (curr != null || !s.isEmpty()) {
// Reach the left most Node of the curr Node
while (curr != null) {
// Place pointer to a tree node on
// the stack before traversing
// the node's left subtree
s.push(curr);
curr = curr.left;
}
// Current must be NULL at this point
curr = s.pop();
ans.add(curr.data);
// we have visited the node and its
// left subtree. Now, it's right
// subtree's turn
curr = curr.right;
}
return ans;
}
static void printList(ArrayList<Integer> v) {
for (int i : v) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] args) {
// Constructed binary tree is
// 1
// / \
// 2 3
// / \
// 4 5
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
ArrayList<Integer> res = inOrder(root);
printList(res);
}
}
# Python program to print inorder traversal
# using stack.
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Iterative function for inorder
# tree traversal
def inOrder(root):
ans = []
stack = []
curr = root
while curr is not None or len(stack) > 0:
# Reach the left most Node of the curr Node
while curr is not None:
# Place pointer to a tree node on
# the stack before traversing
# the node's left subtree
stack.append(curr)
curr = curr.left
# Current must be None at this point
curr = stack.pop()
ans.append(curr.data)
# we have visited the node and its
# left subtree. Now, it's right
# subtree's turn
curr = curr.right
return ans
def printList(v):
print(" ".join(map(str, v)))
if __name__ == "__main__":
# Constructed binary tree is
# 1
# / \
# 2 3
# / \
# 4 5
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
res = inOrder(root)
printList(res)
// C# program to print inorder traversal
// using stack.
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Iterative function for inorder tree traversal
static List<int> InOrder(Node root) {
List<int> ans = new List<int>();
Stack<Node> s = new Stack<Node>();
Node curr = root;
while (curr != null || s.Count > 0) {
// Reach the left most Node of the curr Node
while (curr != null) {
// Place pointer to a tree node on
// the stack before traversing
// the node's left subtree
s.Push(curr);
curr = curr.left;
}
// Current must be NULL at this point
curr = s.Pop();
ans.Add(curr.data);
// we have visited the node and its
// left subtree. Now, it's right
// subtree's turn
curr = curr.right;
}
return ans;
}
static void PrintList(List<int> v) {
foreach (int i in v) {
Console.Write(i + " ");
}
Console.WriteLine();
}
static void Main(string[] args) {
// Constructed binary tree is
// 1
// / \
// 2 3
// / \
// 4 5
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
List<int> res = InOrder(root);
PrintList(res);
}
}
// JavaScript program to print inorder traversal
// using stack.
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Iterative function for inorder tree traversal
function inOrder(root) {
let ans = [];
let s = [];
let curr = root;
while (curr !== null || s.length > 0) {
// Reach the left most Node of the curr Node
while (curr !== null) {
// Place pointer to a tree node on
// the stack before traversing
// the node's left subtree
s.push(curr);
curr = curr.left;
}
// Current must be NULL at this point
curr = s.pop();
ans.push(curr.data);
// we have visited the node and its
// left subtree. Now, it's right
// subtree's turn
curr = curr.right;
}
return ans;
}
function printList(v) {
console.log(v.join(" "));
}
// Constructed binary tree is
// 1
// / \
// 2 3
// / \
// 4 5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
let res = inOrder(root);
printList(res);
Output
4 2 5 1 3
[Expected Approach] Using Morris Traversal Algorithm - O(n) Time and O(1) Space
Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. Please Refer to Inorder Tree Traversal without recursion and without stack! for implementation.