Iterative Postorder Traversal | Set 2 (Using One Stack)
Postorder traversal is a depth-first tree traversal method where each node is processed after its left and right children. While recursive postorder traversal is common, an iterative approach using a single stack offers a more efficient alternative. This article explains how to implement iterative postorder traversal, eliminating recursion while maintaining the correct node visit order, and improving both space and time efficiency.
Refer Iterative Postorder Traversal | Set 1 (Using Two Stacks) for recursive approach
Examples:
Input:
1
/ \
2 3
/ \
4 5
Output: 4 5 2 3 1
Explanation: Postorder traversal (Left->Right->Root) of the tree is 4 5 2 3 1.Input:
8
/ \
1 5
\ / \
7 10 6
\ /
10 6
Output: 10 7 1 6 10 6 5 8
Explanation: Postorder traversal (Left->Right->Root) of the tree is 10 7 1 6 10 6 5 8.
[Expected Approach 1] Pushing the Root Twice - O(n) Time and O(n) Space
In this iterative version, we push each node onto the stack twice: the first push marks the node, and the second one indicates we need to process it after its children. We keep moving to the left child until we reach the leaf nodes, then start processing nodes by popping them from the stack. While popping if we find stack top() is same as root then go for root->right else print root.
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node(int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
vector<int> postOrder(Node* root) {
vector<int> res;
stack<Node*> st;
while (true) {
while (root) {
st.push(root);
st.push(root);
root = root->left;
}
if (st.empty())
return res;
root = st.top();
st.pop();
if (!st.empty() && st.top() == root)
root = root->right;
else {
res.push_back(root->data);
root = nullptr;
}
}
return res;
}
int main() {
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> postOrderList = postOrder(root);
for (auto it : postOrderList)
cout << it << " ";
return 0;
}
import java.util.*;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
public class Main {
static List<Integer> postOrder(Node root) {
List<Integer> res = new ArrayList<>();
Stack<Node> st = new Stack<>();
while (true) {
while (root != null) {
st.push(root);
st.push(root);
root = root.left;
}
if (st.isEmpty())
return res;
root = st.pop();
if (!st.isEmpty() && st.peek() == root)
root = root.right;
else {
res.add(root.data);
root = null;
}
}
}
public static void main(String[] args) {
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<Integer> postOrderList = postOrder(root);
for (int it : postOrderList)
System.out.print(it + " ");
}
}
# Python implementation
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
def postOrder(root):
res = []
st = []
while True:
while root:
st.append(root)
st.append(root)
root = root.left
if not st:
return res
root = st.pop()
if st and st[-1] == root:
root = root.right
else:
res.append(root.data)
root = None
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
postOrderList = postOrder(root)
print(' '.join(map(str, postOrderList)))
// C# implementation
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 {
static List<int> PostOrder(Node root) {
List<int> res = new List<int>();
Stack<Node> st = new Stack<Node>();
while (true) {
while (root != null) {
st.Push(root);
st.Push(root);
root = root.left;
}
if (st.Count == 0)
return res;
root = st.Pop();
if (st.Count > 0 && st.Peek() == root)
root = root.right;
else {
res.Add(root.data);
root = null;
}
}
}
static void Main() {
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> postOrderList = PostOrder(root);
Console.WriteLine(string.Join(" ", postOrderList));
}
}
// JavaScript implementation
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
function postOrder(root) {
const res = [];
const st = [];
while (true) {
while (root) {
st.push(root);
st.push(root);
root = root.left;
}
if (st.length === 0)
return res;
root = st.pop();
if (st.length > 0 && st[st.length - 1] === root)
root = root.right;
else {
res.push(root.data);
root = null;
}
}
}
const 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);
const postOrderList = postOrder(root);
console.log(postOrderList.join(' '));
Output
4 5 2 3 1
[Expected Approach 2] Moving both Root and Right - O(n) Time and O(n) Space
The idea is to move down to leftmost node using left pointer. While moving down, push root and root's right child to stack. Once we reach leftmost node, print it if it doesn't have a right child. If it has a right child, then change root so that the right child is processed before.
Following is detailed algorithm.
1.1 Create an empty stack
2.1 Do following while root is not NULL
a) Push root's right child and then root to stack.
b) Set root as root's left child.
2.2 Pop an item from stack and set it as root.
a) If the popped item has a right child and the right child
is at top of stack, then remove the right child from stack,
push the root back and set root as root's right child.
b) Else print root's data and set root as NULL.
2.3 Repeat steps 2.1 and 2.2 while stack is not empty.
// C++ program for iterative postorder
// traversal using one stack
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Function for iterative post-order
// traversal using one stack
vector<int> postOrder(Node* root) {
vector<int> result;
if (root == nullptr) {
return result;
}
stack<Node*> stk;
// Step 2.1: Process until root becomes null
while (root != nullptr || !stk.empty()) {
// Move to the leftmost node and push
// right child and root
while (root != nullptr) {
if (root->right != nullptr) {
stk.push(root->right);
}
stk.push(root);
root = root->left;
}
// Step 2.2: Pop an item from the stack
root = stk.top();
stk.pop();
// Step 2.2a: If the popped node has a right child
// and the right child is on the top of the stack
if (!stk.empty() && root->right != nullptr
&& stk.top() == root->right) {
stk.pop();
stk.push(root);
root = root->right;
}
else {
// Step 2.2b: Else, print the node's
// data and set root as null
result.push_back(root->data);
root = nullptr;
}
}
return result;
}
void printArray(const vector<int>& arr) {
for (int data : arr) {
cout << data << " ";
}
cout << endl;
}
int main() {
// Representation of input binary tree:
// 1
// / \
// 2 3
// / \
// 4 5
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->right->left = new Node(4);
root->right->right = new Node(5);
vector<int> result = postOrder(root);
printArray(result);
return 0;
}
// C program for iterative postorder
// traversal using one stack
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function for iterative post-order
// traversal using one stack
int* postOrder(struct Node* root, int* size) {
*size = 0;
if (root == NULL) return NULL;
struct Node* stk[100];
int result[100];
int top = -1, resIndex = 0;
// Step 2.1: Process until root becomes null
while (root != NULL || top >= 0) {
// Move to the leftmost node and push
// right child and root
while (root != NULL) {
if (root->right != NULL) {
stk[++top] = root->right;
}
stk[++top] = root;
root = root->left;
}
// Step 2.2: Pop an item from the stack
root = stk[top--];
// Step 2.2a: If the popped node has a right child
// and the right child is on the top of the stack
if (top >= 0 && root->right != NULL
&& stk[top] == root->right) {
top--;
stk[++top] = root;
root = root->right;
}
else {
// Step 2.2b: Else, add the node's data
result[resIndex++] = root->data;
root = NULL;
}
}
int* output = (int*)malloc(resIndex * sizeof(int));
for (int i = 0; i < resIndex; i++) {
output[i] = result[i];
}
*size = resIndex;
return output;
}
void printArray(int* arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
struct Node* createNode(int x) {
struct Node* newNode
= (struct Node*)malloc(sizeof(struct Node));
newNode->data = x;
newNode->left = newNode->right = NULL;
return newNode;
}
int main() {
// Representation of input binary tree:
// 1
// / \
// 2 3
// / \
// 4 5
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->right->left = createNode(4);
root->right->right = createNode(5);
int size;
int* result = postOrder(root, &size);
printArray(result, size);
return 0;
}
// Java program for iterative postorder
// traversal using one stack
import java.util.ArrayList;
import java.util.Stack;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
public class GfG {
// Function for iterative post-order
// traversal using one stack
static ArrayList<Integer> postOrder(Node root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Stack<Node> stk = new Stack<>();
// Step 2.1: Process until root becomes null
while (root != null || !stk.isEmpty()) {
// Move to the leftmost node and push
// right child and root
while (root != null) {
if (root.right != null) {
stk.push(root.right);
}
stk.push(root);
root = root.left;
}
// Step 2.2: Pop an item from the stack
root = stk.pop();
// Step 2.2a: If the popped node has a right child
// and the right child is on the top of the stack
if (!stk.isEmpty() && root.right != null
&& stk.peek() == root.right) {
stk.pop();
stk.push(root);
root = root.right;
}
else {
// Step 2.2b: Else, print the node's
// data and set root as null
result.add(root.data);
root = null;
}
}
return result;
}
static void printArray(ArrayList<Integer> arr) {
for (int data : arr) {
System.out.print(data + " ");
}
System.out.println();
}
public static void main(String[] args) {
// Representation of input binary tree:
// 1
// / \
// 2 3
// / \
// 4 5
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(5);
ArrayList<Integer> result = postOrder(root);
printArray(result);
}
}
# Python program for iterative postorder
# traversal using one stack
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Function for iterative post-order traversal
# using one stack
def postOrder(root):
result = []
if root is None:
return result
stk = []
# Step 2.1: Process until root becomes null
while root is not None or len(stk) > 0:
# Move to the leftmost node and push
# right child and root
while root is not None:
if root.right is not None:
stk.append(root.right)
stk.append(root)
root = root.left
# Step 2.2: Pop an item from the stack
root = stk.pop()
# Step 2.2a: If the popped node has a right child
# and the right child is on the top of the stack
if len(stk) > 0 and root.right is not None and stk[-1] == root.right:
stk.pop()
stk.append(root)
root = root.right
else:
# Step 2.2b: Else, add the node's
# data and set root as null
result.append(root.data)
root = None
return result
def printArray(arr):
print(" ".join(map(str, arr)))
if __name__ == "__main__":
# Representation of input binary tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.right.left = Node(4)
root.right.right = Node(5)
result = postOrder(root)
printArray(result)
// C# program for iterative postorder
// traversal using one 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 for iterative post-order
// traversal using one stack
static List<int> postOrder(Node root) {
List<int> result = new List<int>();
if (root == null) {
return result;
}
Stack<Node> stk = new Stack<Node>();
// Step 2.1: Process until root becomes null
while (root != null || stk.Count > 0) {
// Move to the leftmost node and push
// right child and root
while (root != null) {
if (root.right != null) {
stk.Push(root.right);
}
stk.Push(root);
root = root.left;
}
// Step 2.2: Pop an item from the stack
root = stk.Pop();
// Step 2.2a: If the popped node has a right child
// and the right child is on the top of the stack
if (stk.Count > 0 && root.right != null
&& stk.Peek() == root.right) {
stk.Pop();
stk.Push(root);
root = root.right;
} else {
// Step 2.2b: Else, add the node's
// data and set root as null
result.Add(root.data);
root = null;
}
}
return result;
}
static void printArray(List<int> arr) {
foreach (int data in arr) {
Console.Write(data + " ");
}
Console.WriteLine();
}
public static void Main(string[] args) {
// Representation of input binary tree:
// 1
// / \
// 2 3
// / \
// 4 5
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(5);
List<int> result = postOrder(root);
printArray(result);
}
}
// JavaScript program for iterative postorder
// traversal using one stack
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Function for iterative post-order
// traversal using one stack
function postOrder(root) {
const result = [];
if (root === null) {
return result;
}
const stk = [];
// Step 2.1: Process until root becomes null
while (root !== null || stk.length > 0) {
// Move to the leftmost node and push
// right child and root
while (root !== null) {
if (root.right !== null) {
stk.push(root.right);
}
stk.push(root);
root = root.left;
}
// Step 2.2: Pop an item from the stack
root = stk.pop();
// Step 2.2a: If the popped node has a right child
// and the right child is on the top of the stack
if (stk.length > 0 && root.right !== null
&& stk[stk.length - 1] === root.right) {
stk.pop();
stk.push(root);
root = root.right;
}
else {
// Step 2.2b: Else, add the node's
// data and set root as null
result.push(root.data);
root = null;
}
}
return result;
}
function printArray(arr) {
console.log(arr.join(" "));
}
// Representation of input binary tree:
// 1
// / \
// 2 3
// / \
// 4 5
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(5);
const result = postOrder(root);
printArray(result);
Output
2 4 5 3 1
Let us consider the following tree
Following are the steps to print postorder traversal of the above tree using one stack.
1. Right child of 1 exists. Push 3 to stack. Push 1 to stack. Move to left child.
Stack: 3, 1
2. Right child of 2 exists. Push 5 to stack. Push 2 to stack. Move to left child.
Stack: 3, 1, 5, 2
3. Right child of 4 doesn't exist. Push 4 to stack. Move to left child.
Stack: 3, 1, 5, 2, 4
4. Current node is NULL. Pop 4 from stack. Right child of 4 doesn't exist. Print 4. Set current node to NULL.
Stack: 3, 1, 5, 2
5. Current node is NULL. Pop 2 from stack. Since right child of 2 equals stack top element, pop 5 from stack. Now push 2 to stack. Move current node to right child of 2 i.e. 5
Stack: 3, 1, 2
6. Right child of 5 doesn't exist. Push 5 to stack. Move to left child.
Stack: 3, 1, 2, 5
7. Current node is NULL. Pop 5 from stack. Right child of 5 doesn't exist. Print 5. Set current node to NULL.
Stack: 3, 1, 2
8. Current node is NULL. Pop 2 from stack. Right child of 2 is not equal to stack top element. Print 2. Set current node to NULL.
Stack: 3, 1
9. Current node is NULL. Pop 1 from stack. Since right child of 1 equals stack top element, pop 3 from stack. Now push 1 to stack. Move current node to right child of 1 i.e. 3
Stack: 1
10. Repeat the same as above steps and Print 6, 7 and 3.
Pop 1 and Print 1.
Time Complexity: O(n), where n is the number of nodes, as each node is visited once during traversal.
Auxiliary Space: O(h), where h is the height of the tree, due to the stack, with h being O(n) in the worst case for a skewed tree.
[Expected Approach 3] Tracking Last Visited Node - O(n) Time and O(n) Space
The traversal order in postorder is left child, right child, and then the node itself. Instead of recursion, the algorithm simulates the recursive calls using a stack. It first pushes nodes onto the stack as it moves down the left side of the tree. Once it reaches a leaf, it starts processing the nodes by checking if the right child has been visited. If not, it traverses the right subtree; otherwise, it processes the node and adds it to the result.
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <sstream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = nullptr;
right = nullptr;
}
};
vector<int> postOrder(Node* root) {
vector<int> res;
if (!root) return res;
stack<Node*> s;
Node* lastVisited = nullptr;
while (!s.empty() || root) {
// Keep moving to the left
// until we reach a null
if (root) {
s.push(root);
root = root->left;
}
else {
// Take out an item from stack
Node* peekNode = s.top();
// If the taken out item has a
// right child and the right child
// is not visited, move to the right
if (peekNode->right && lastVisited != peekNode->right) {
root = peekNode->right;
// If there is no right child
// or the right child is already
// visited, then add peekNode to the
// result and remove from the stack
} else {
res.push_back(peekNode->data);
lastVisited = s.top();
s.pop();
}
}
}
return res;
}
// Driver program to test above functions
int main() {
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);
root->right->left = new Node(6);
root->right->right = new Node(7);
printf("Post order traversal of binary tree is:\n[");
vector<int> res = postOrder(root);
for (auto it : res)
cout << it << " ";
printf("]");
return 0;
}
import java.util.*;
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = right = null;
}
}
public class Main {
static List<Integer> postOrder(Node root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
Stack<Node> s = new Stack<>();
Node lastVisited = null;
while (!s.isEmpty() || root != null) {
if (root != null) {
s.push(root);
root = root.left;
} else {
Node peekNode = s.peek();
if (peekNode.right != null && lastVisited != peekNode.right) {
root = peekNode.right;
} else {
res.add(peekNode.data);
lastVisited = s.pop();
}
}
}
return res;
}
public static void main(String[] args) {
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);
root.right.left = new Node(6);
root.right.right = new Node(7);
System.out.println("Post order traversal of binary tree is:");
List<Integer> res = postOrder(root);
System.out.print("[");
for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i) + (i < res.size() - 1 ? " " : ""));
}
System.out.println("]");
}
}
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def postOrder(root):
res = []
if root is None:
return res
s = []
lastVisited = None
while s or root:
if root:
s.append(root)
root = root.left
else:
peekNode = s[-1]
if peekNode.right and lastVisited != peekNode.right:
root = peekNode.right
else:
res.append(peekNode.data)
lastVisited = s.pop()
return res
# Driver program to test above functions
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
print("Post order traversal of binary tree is:")
res = postOrder(root)
print("[", end='')
print(' '.join(map(str, res)), end='')
print("]")
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int val) {
data = val;
left = right = null;
}
}
class Program {
static List<int> PostOrder(Node root) {
List<int> res = new List<int>();
if (root == null) return res;
Stack<Node> s = new Stack<Node>();
Node lastVisited = null;
while (s.Count > 0 || root != null) {
if (root != null) {
s.Push(root);
root = root.left;
} else {
Node peekNode = s.Peek();
if (peekNode.right != null && lastVisited != peekNode.right) {
root = peekNode.right;
} else {
res.Add(peekNode.data);
lastVisited = s.Pop();
}
}
}
return res;
}
static void Main() {
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);
root.right.left = new Node(6);
root.right.right = new Node(7);
Console.WriteLine("Post order traversal of binary tree is:");
List<int> res = PostOrder(root);
Console.Write("[");
Console.Write(string.Join(" ", res));
Console.WriteLine("]");
}
}
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
function postOrder(root) {
let res = [];
if (root === null) {
return res;
}
let s = [];
let lastVisited = null;
while (s.length > 0 || root) {
if (root) {
s.push(root);
root = root.left;
} else {
let peekNode = s[s.length - 1];
if (peekNode.right && lastVisited !== peekNode.right) {
root = peekNode.right;
} else {
res.push(peekNode.data);
lastVisited = s.pop();
}
}
}
return res;
}
// Driver program to test above functions
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);
root.right.left = new Node(6);
root.right.right = new Node(7);
console.log("Post order traversal of binary tree is:");
let res = postOrder(root);
console.log('[', res.join(' '), ']');
Output
Post order traversal of binary tree is: [4 5 2 6 7 3 1 ]