Iterative Postorder Traversal | Set 1 (Using Two Stacks)
Last Updated : 04 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report
Given a binary tree, the task is to find the postorder traversal of the tree without using recursion.
Examples:
Input:
Output: 4 5 2 3 1 Explanation: Postorder traversal (Left->Right->Root) of the tree is 4 5 2 3 1.
Input:
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 .
Approach:
The idea is to push reverse Postorder traversal to a stack. Once we have the reversed postorder traversal in a stack, we can just pop all items one by one from the stack and print them; this order of printing will be in postorder because of the LIFO property of stacks. Now the question is, how to get reversed postorder elements in a stack - the second stack is used for this purpose. For example, in the following tree, we need to get 1, 3, 7, 6, 2, 5, 4 in a stack. If we take a closer look at this sequence, we can observe that this sequence is very similar to the preorder traversal. The only difference is that the right child is visited before left child, and therefore the sequence is “root right left” instead of “root left right”. So, we can do something like iterative preorder traversal with the following differences: a) Instead of printing an item, we push it to a stack. b) We push the left subtree before the right subtree.
Follow the steps below to solve the problem:
Push root to first stack.
Loop until first stack is not empty
Pop a node from first stack and push it to second stack
Push left and right children of the popped node to first stack
Print contents of second stack
Consider the following tree:
Following are the steps to print Postorder traversal of the above tree using two stacks:
1. Push 1 to first stack First stack: 1 Second stack: empty
2. Pop 1 from first stack and push it to second stack. Push left and right children of 1 to first stack First stack: 2, 3 Second stack: 1
3. Pop 3 from first stack and push it to second stack. Push left and right children of 3 to first stack First stack: 2, 6, 7 Second stack: 1, 3
4. Pop 7 from first stack and push it to second stack. First stack: 2, 6 Second stack: 1, 3, 7
5. Pop 6 from first stack and push it to second stack. First stack: 2 Second stack: 1, 3, 7, 6
6. Pop 2 from first stack and push it to second stack. Push left and right children of 2 to first stack First stack: 4, 5 Second stack: 1, 3, 7, 6, 2
7. Pop 5 from first stack and push it to second stack. First stack: 4 Second stack: 1, 3, 7, 6, 2, 5
8. Pop 4 from first stack and push it to second stack. First stack: Empty Second stack: 1, 3, 7, 6, 2, 5, 4
The algorithm stops here since there are no more items in the first stack. Observe that the contents of second stack are in postorder manner. Print them.
Below is the implementation of the above approach:
C++
// C++ program to o find the postorder // traversal using 2 Stacks#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to do post-order traversal// using two stacks iterativelyvector<int>postOrder(Node*root){vector<int>result;if(root==nullptr){returnresult;}// Create two stacksstack<Node*>stk1,stk2;// Push root to first stackstk1.push(root);Node*curr;// Run while first stack is not emptywhile(!stk1.empty()){// Pop from s1 and push it to s2curr=stk1.top();stk1.pop();stk2.push(curr);// Push left and right children of the// popped nodeif(curr->left){stk1.push(curr->left);}if(curr->right){stk1.push(curr->right);}}// Collect all elements from second stackwhile(!stk2.empty()){curr=stk2.top();stk2.pop();result.push_back(curr->data);}returnresult;}voidprintArray(constvector<int>&arr){for(intdata:arr){cout<<data<<" ";}cout<<endl;}intmain(){// Representation of input binary tree:// 1// / \ // 2 3// / \ // 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);vector<int>result=postOrder(root);printArray(result);return0;}
C
// C program to find the postorder// traversal using 2 stacks#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// Stack structure for holding nodesstructStack{inttop;intcapacity;structNode*array[100];};// Function to create a stackstructStackcreateStack(intcapacity){structStackstack;stack.top=-1;stack.capacity=capacity;returnstack;}// Function to check if stack is emptyintisEmpty(structStack*stack){returnstack->top==-1;}// Function to push node onto the stackvoidpush(structStack*stack,structNode*node){stack->array[++stack->top]=node;}// Function to pop node from the stackstructNode*pop(structStack*stack){returnstack->array[stack->top--];}// Function to perform postorder traversal // using two stacksvoidpostOrder(structNode*root){if(root==NULL){return;}structStackstk1=createStack(100);structStackstk2=createStack(100);structNode*curr;// Push root to first stackpush(&stk1,root);// Loop while stk1 is not emptywhile(!isEmpty(&stk1)){// Pop from stk1 and push it to stk2curr=pop(&stk1);push(&stk2,curr);// Push left and right children of popped nodeif(curr->left){push(&stk1,curr->left);}if(curr->right){push(&stk1,curr->right);}}// Print nodes in stk2 which gives postorderwhile(!isEmpty(&stk2)){curr=pop(&stk2);printf("%d ",curr->data);}}structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->left=node->right=NULL;returnnode;}intmain(){// Representation of input binary tree:// 1// / \ // 2 3// / \ // 4 5structNode*root=createNode(1);root->left=createNode(2);root->right=createNode(3);root->left->left=createNode(4);root->left->right=createNode(5);postOrder(root);return0;}
Java
// Java program to o find the postorder // traversal using 2 Stacksimportjava.util.ArrayList;importjava.util.Stack;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to do post-order traversal // using two stacksstaticArrayList<Integer>postOrder(Noderoot){ArrayList<Integer>result=newArrayList<>();if(root==null){returnresult;}// Create two stacksStack<Node>stk1=newStack<>();Stack<Node>stk2=newStack<>();// Push root to first stackstk1.push(root);Nodecurr;// Run while first stack is not emptywhile(!stk1.isEmpty()){// Pop from stk1 and push it to stk2curr=stk1.pop();stk2.push(curr);// Push left and right children of // the popped nodeif(curr.left!=null){stk1.push(curr.left);}if(curr.right!=null){stk1.push(curr.right);}}// Collect all elements from second stackwhile(!stk2.isEmpty()){curr=stk2.pop();result.add(curr.data);}returnresult;}staticvoidprintArray(ArrayList<Integer>arr){for(intdata:arr){System.out.print(data+" ");}System.out.println();}publicstaticvoidmain(String[]args){// Representation of input binary tree:// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);ArrayList<Integer>result=postOrder(root);printArray(result);}}
Python
# Python program to o find the postorder # traversal using 2 StacksclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to do post-order traversal # using two stacksdefpostOrder(root):result=[]ifrootisNone:returnresult# Create two stacksstk1=[]stk2=[]# Push root to first stackstk1.append(root)# Run while first stack is not emptywhilestk1:# Pop from stk1 and push it to stk2curr=stk1.pop()stk2.append(curr)# Push left and right children of # the popped nodeifcurr.left:stk1.append(curr.left)ifcurr.right:stk1.append(curr.right)# Collect all elements from second stackwhilestk2:curr=stk2.pop()result.append(curr.data)returnresultdefprintArray(arr):print(" ".join(map(str,arr)))if__name__=="__main__":# Representation of input binary tree:# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)result=postOrder(root)printArray(result)
C#
// C# program to o find the postorder // traversal using 2 StacksusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to do post-order traversal // using two stacksstaticList<int>postOrder(Noderoot){List<int>result=newList<int>();if(root==null){returnresult;}// Create two stacksStack<Node>stk1=newStack<Node>();Stack<Node>stk2=newStack<Node>();// Push root to first stackstk1.Push(root);// Run while first stack is not emptywhile(stk1.Count>0){// Pop from stk1 and push it to stk2Nodecurr=stk1.Pop();stk2.Push(curr);// Push left and right children of // the popped nodeif(curr.left!=null){stk1.Push(curr.left);}if(curr.right!=null){stk1.Push(curr.right);}}// Collect all elements from second stackwhile(stk2.Count>0){Nodecurr=stk2.Pop();result.Add(curr.data);}returnresult;}staticvoidprintArray(List<int>arr){foreach(intdatainarr){Console.Write(data+" ");}Console.WriteLine();}staticvoidMain(string[]args){// Representation of input binary tree:// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);List<int>result=postOrder(root);printArray(result);}}
JavaScript
// JavaScript program to find the postorder // traversal using 2 StacksclassNode{constructor(key){this.key=key;this.left=null;this.right=null;}}// Function to perform postorder traversal // using two stacksfunctionpostOrder(root){constans=[];if(!root)returnans;conststk1=[root];conststk2=[];// Loop while stk1 is not emptywhile(stk1.length>0){constnode=stk1.pop();// Push node's key to stk2stk2.push(node.key);// Push left and right children to stk1if(node.left)stk1.push(node.left);if(node.right)stk1.push(node.right);}// Collect nodes from s2 in postorderwhile(stk2.length>0){ans.push(stk2.pop());}returnans;}// Representation of input binary tree:// 1// / \// 2 3// / \// 4 5constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);constresult=postOrder(root);console.log(result.join(' '));
Output
4 5 2 3 1
Time complexity: O(n), since the algorithm processes each node exactly twice (once when pushed to s1 and once when popped from s2), where n is the number of nodes. Auxiliary space: O(n), due to the two stacks, each holding up to n nodes at different points in the traversal.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.