Iterative Postorder Traversal | Set 2 (Using One Stack)
Last Updated :
11 Mar, 2024
We have discussed a simple iterative postorder traversal using two stacks in the previous post. In this post, an approach with only one stack is discussed.
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.
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.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode( int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return node;
}
vector< int > postOrderIterative( struct Node* root)
{
vector< int > postOrderList;
if (root == NULL)
return postOrderList;
stack<Node*> S;
S.push(root);
Node* prev = NULL;
while (!S.empty()) {
auto current = S.top();
if (prev == NULL || prev->left == current
|| prev->right == current) {
if (current->left)
S.push(current->left);
else if (current->right)
S.push(current->right);
else {
S.pop();
postOrderList.push_back(current->data);
}
}
else if (current->left == prev) {
if (current->right)
S.push(current->right);
else {
S.pop();
postOrderList.push_back(current->data);
}
}
else if (current->right == prev) {
S.pop();
postOrderList.push_back(current->data);
}
prev = current;
}
return postOrderList;
}
int main()
{
struct Node* root = NULL;
root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
printf ( "Post order traversal of binary tree is :\n" );
printf ( "[" );
vector< int > postOrderList = postOrderIterative(root);
for ( auto it : postOrderList)
cout << it << " " ;
printf ( "]" );
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
struct Node {
int data;
struct Node *left, *right;
};
struct Stack {
int size;
int top;
struct Node** array;
};
struct Node* newNode( int data)
{
struct Node* node
= ( struct Node*) malloc ( sizeof ( struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
struct Stack* createStack( int size)
{
struct Stack* stack
= ( struct Stack*) malloc ( sizeof ( struct Stack));
stack->size = size;
stack->top = -1;
stack->array = ( struct Node**) malloc (
stack->size * sizeof ( struct Node*));
return stack;
}
int isFull( struct Stack* stack)
{
return stack->top - 1 == stack->size;
}
int isEmpty( struct Stack* stack)
{
return stack->top == -1;
}
void push( struct Stack* stack, struct Node* node)
{
if (isFull(stack))
return ;
stack->array[++stack->top] = node;
}
struct Node* pop( struct Stack* stack)
{
if (isEmpty(stack))
return NULL;
return stack->array[stack->top--];
}
struct Node* peek( struct Stack* stack)
{
if (isEmpty(stack))
return NULL;
return stack->array[stack->top];
}
void postOrderIterative( struct Node* root)
{
if (root == NULL)
return ;
struct Stack* stack = createStack(MAX_SIZE);
do {
while (root) {
if (root->right)
push(stack, root->right);
push(stack, root);
root = root->left;
}
root = pop(stack);
if (root->right && peek(stack) == root->right) {
pop(stack);
push(stack, root);
root = root->right;
}
else
{
printf ( "%d " , root->data);
root = NULL;
}
} while (!isEmpty(stack));
}
int main()
{
struct Node* root = NULL;
root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
printf ( "Post order traversal of binary tree is :\n" );
printf ( "[" );
postOrderIterative(root);
printf ( "]" );
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Stack;
class Node {
int data;
Node left, right;
Node( int item)
{
data = item;
left = right;
}
}
class BinaryTree {
Node root;
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> postOrderIterative(Node node)
{
Stack<Node> S = new Stack<Node>();
if (node == null )
return list;
S.push(node);
Node prev = null ;
while (!S.isEmpty()) {
Node current = S.peek();
if (prev == null || prev.left == current || prev.right == current) {
if (current.left != null )
S.push(current.left);
else if (current.right != null )
S.push(current.right);
else {
S.pop();
list.add(current.data);
}
}
else if (current.left == prev) {
if (current.right != null )
S.push(current.right);
else {
S.pop();
list.add(current.data);
}
}
else if (current.right == prev) {
S.pop();
list.add(current.data);
}
prev = current;
}
return list;
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 1 );
tree.root.left = new Node( 2 );
tree.root.right = new Node( 3 );
tree.root.left.left = new Node( 4 );
tree.root.left.right = new Node( 5 );
tree.root.right.left = new Node( 6 );
tree.root.right.right = new Node( 7 );
ArrayList<Integer> mylist = tree.postOrderIterative(tree.root);
System.out.println(
"Post order traversal of binary tree is :" );
System.out.println(mylist);
}
}
|
C#
using System;
using System.Collections.Generic;
class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right;
}
}
public class BinaryTree
{
Node root;
List< int > list = new List< int >();
List< int > postOrderIterative(Node node)
{
Stack<Node> S = new Stack<Node>();
if (node == null )
return list;
S.Push(node);
Node prev = null ;
while (S.Count != 0)
{
Node current = S.Peek();
if (prev == null || prev.left == current ||
prev.right == current)
{
if (current.left != null )
S.Push(current.left);
else if (current.right != null )
S.Push(current.right);
else
{
S.Pop();
list.Add(current.data);
}
}
else if (current.left == prev)
{
if (current.right != null )
S.Push(current.right);
else
{
S.Pop();
list.Add(current.data);
}
}
else if (current.right == prev)
{
S.Pop();
list.Add(current.data);
}
prev = current;
}
return list;
}
public static void Main(String []args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
List< int > mylist = tree.postOrderIterative(tree.root);
Console.WriteLine( "Post order traversal of binary tree is :" );
foreach ( int i in mylist)
Console.Write(i+ " " );
}
}
|
Javascript
<script>
class Node
{
constructor(item)
{
this .data=item;
this .left= null ;
this .right= null ;
}
}
let root;
let list = [];
function postOrderIterative(node)
{
let S = [];
if (node == null )
return list;
S.push(node);
let prev = null ;
while (S.length!=0)
{
let current = S[S.length-1];
if (prev == null || prev.left == current ||
prev.right == current)
{
if (current.left != null )
S.push(current.left);
else if (current.right != null )
S.push(current.right);
else
{
S.pop();
list.push(current.data);
}
}
else if (current.left == prev)
{
if (current.right != null )
S.push(current.right);
else
{
S.pop();
list.push(current.data);
}
}
else if (current.right == prev)
{
S.pop();
list.push(current.data);
}
prev = current;
}
return list;
}
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);
let mylist = postOrderIterative(root);
document.write( "Post order traversal of binary tree is :<br>" );
for (let i = 0; i < mylist.length; i++)
{
document.write(mylist[i]+ " " );
}
</script>
|
Python3
ans = []
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def peek(stack):
if len (stack) > 0 :
return stack[ - 1 ]
return None
def postOrderIterative(root):
if root is None :
return
stack = []
while ( True ):
while (root):
if root.right is not None :
stack.append(root.right)
stack.append(root)
root = root.left
root = stack.pop()
if (root.right is not None and
peek(stack) = = root.right):
stack.pop()
stack.append(root)
root = root.right
else :
ans.append(root.data)
root = None
if ( len (stack) < = 0 ):
break
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" )
postOrderIterative(root)
print (ans)
|
Output
Post order traversal of binary tree is :
[4 5 2 6 7 3 1 ]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2:Â
Push directly root node two times while traversing to the left. While popping if you find stack top() is same as root then go for root->right else print root.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode( int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return node;
}
vector< int > postOrderIterative( struct Node* root)
{
vector< int > postOrderList;
stack<Node*> st;
while ( true ) {
while (root) {
st.push(root);
st.push(root);
root = root->left;
}
if (st.empty())
return postOrderList;
root = st.top();
st.pop();
if (!st.empty() && st.top() == root)
root = root->right;
else {
postOrderList.push_back(root->data);
root = NULL;
}
}
return postOrderList;
}
int main()
{
struct Node* root = NULL;
root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
printf ( "Post order traversal of binary tree is :\n" );
printf ( "[" );
vector< int > postOrderList = postOrderIterative(root);
for ( auto it : postOrderList)
cout << it << " " ;
printf ( "]" );
return 0;
}
|
Java
import java.util.Stack;
class Node
{
int data;
Node left, right;
Node( int item)
{
data = item;
left = right;
}
}
class PostOrder
{
Node root;
private void postOrderIterative(Node root) {
Stack<Node> stack = new Stack<>();
while ( true ) {
while (root != null ) {
stack.push(root);
stack.push(root);
root = root.left;
}
if (stack.empty()) return ;
root = stack.pop();
if (!stack.empty() && stack.peek() == root) root = root.right;
else {
System.out.print(root.data + " " ); root = null ;
}
}
}
public static void main(String args[])
{
PostOrder tree = new PostOrder();
tree.root = new Node( 1 );
tree.root.left = new Node( 2 );
tree.root.right = new Node( 3 );
tree.root.left.left = new Node( 4 );
tree.root.left.right = new Node( 5 );
tree.root.right.left = new Node( 6 );
tree.root.right.right = new Node( 7 );
System.out.println( "Post order traversal of binary tree is :" );
tree.postOrderIterative(tree.root);
}
}
|
C#
using System;
using System.Collections.Generic;
public
class Node
{
public
int data;
public
Node left, right;
public
Node( int item)
{
data = item;
left = right;
}
}
public class PostOrder
{
Node root;
private void postOrderIterative(Node root)
{
Stack<Node> stack = new Stack<Node>();
while ( true )
{
while (root != null )
{
stack.Push(root);
stack.Push(root);
root = root.left;
}
if (stack.Count == 0) return ;
root = stack.Pop();
if (stack.Count != 0 && stack.Peek() == root) root = root.right;
else
{
Console.Write(root.data + " " ); root = null ;
}
}
}
public static void Main(String []args)
{
PostOrder tree = new PostOrder();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
Console.WriteLine( "Post order traversal of binary tree is :" );
tree.postOrderIterative(tree.root);
}
}
|
Javascript
<script>
class Node {
constructor(item) {
this .data = item;
this .left = null ;
this .right = null ;
}
}
class PostOrder {
constructor() {
this .root = null ;
}
postOrderIterative(root) {
var stack = [];
while ( true ) {
while (root != null ) {
stack.push(root);
stack.push(root);
root = root.left;
}
if (stack.length == 0) return ;
root = stack.pop();
if (stack.length != 0 && stack[stack.length - 1] == root)
root = root.right;
else {
document.write(root.data + " " );
root = null ;
}
}
}
}
var tree = new PostOrder();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
document.write( "Post order traversal of binary tree is :<br>" );
tree.postOrderIterative(tree.root);
</script>
|
Python3
class Node:
def __init__( self , x):
self .data = x
self .right = None
self .left = None
def postOrderIterative(root):
stack = []
while ( True ):
while (root ! = None ):
stack.append(root)
stack.append(root)
root = root.left
if ( len (stack) = = 0 ):
return
root = stack.pop()
if ( len (stack) > 0 and stack[ - 1 ] = = root):
root = root.right
else :
print (root.data, end = " " )
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 )
root.right.left = Node( 6 )
root.right.right = Node( 7 )
print ( "Post order traversal of binary tree is :" )
postOrderIterative(root)
|
Output
Post order traversal of binary tree is :
[4 5 2 6 7 3 1 ]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3 (Iterative PostOrder Traversal Using Stack and Hashing) : Â
- Create a Stack for finding the postorder traversal and an unordered map for hashing to mark the visited nodes.
- Initially push the root node in the stack and follow the below steps until the stack is not empty. The stack will get empty when postorder traversal is stored in our answer container data structure.
- Mark the current node (node on the top of stack) as visited in our hashtable.
- If the left child of the current node is not NULL and not visited then push it into the stack.
- Otherwise, if the right child of the top node is not NULL and not visited push it into the stack
- If none of the above two conditions holds true then add the value of the current node to our answer and remove(pop) the current node from the stack.
- When the stack gets empty, we will have postorder traversal stored in our answer data structure (array or vector).
C++
#include <bits/stdc++.h>
using namespace std;
#define MAX_HEIGHT 100000
struct Node {
int data;
Node* left;
Node* right;
};
Node* newNode( int val)
{
Node* temp = new Node;
temp->data = val;
temp->left = NULL;
temp->right = NULL;
return temp;
}
Node* buildTree(string str)
{
if (str.length() == 0 || str[0] == 'N' )
return NULL;
vector<string> ip;
istringstream iss(str);
for (string str; iss >> str;)
ip.push_back(str);
Node* root = newNode(stoi(ip[0]));
queue<Node*> queue;
queue.push(root);
int i = 1;
while (!queue.empty() && i < ip.size()) {
Node* currNode = queue.front();
queue.pop();
string currVal = ip[i];
if (currVal != "N" ) {
currNode->left = newNode(stoi(currVal));
queue.push(currNode->left);
}
i++;
if (i >= ip.size())
break ;
currVal = ip[i];
if (currVal != "N" ) {
currNode->right = newNode(stoi(currVal));
queue.push(currNode->right);
}
i++;
}
return root;
}
vector< int > postOrder(Node* node)
{
stack<Node*> s;
vector< int > post;
unordered_map<Node*, int > vis;
s.push(node);
while (!s.empty()) {
vis[s.top()] = 1;
if (s.top()->left != 0) {
if (!vis[s.top()->left]) {
s.push(s.top()->left);
continue ;
}
}
if (s.top()->right != 0) {
if (!vis[s.top()->right]) {
s.push(s.top()->right);
continue ;
}
}
post.push_back(s.top()->data);
s.pop();
}
return post;
}
int main()
{
string s = "1 2 3 4 5 6 7" ;
Node* root = buildTree(s);
vector< int > ans;
ans = postOrder(root);
cout << "Post order traversal of binary tree is :\n" ;
for ( int i = 0; i < ans.size(); i++)
cout << ans[i] << " " ;
cout << endl;
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node left, right;
Node( int item) {
data = item;
left = right = null ;
}
}
public class Main {
static Node buildTree(String str) {
if (str.length() == 0 || str.charAt( 0 ) == 'N' )
return null ;
String[] ip = str.split( " " );
Node root = new Node(Integer.parseInt(ip[ 0 ]));
Queue<Node> queue = new LinkedList<>();
queue.add(root);
int i = 1 ;
while (!queue.isEmpty() && i < ip.length) {
Node currNode = queue.poll();
String currVal = ip[i];
if (!currVal.equals( "N" )) {
currNode.left = new Node(Integer.parseInt(currVal));
queue.add(currNode.left);
}
i++;
if (i >= ip.length)
break ;
currVal = ip[i];
if (!currVal.equals( "N" )) {
currNode.right = new Node(Integer.parseInt(currVal));
queue.add(currNode.right);
}
i++;
}
return root;
}
static List<Integer> postOrder(Node node) {
Stack<Node> s = new Stack<>();
List<Integer> post = new ArrayList<>();
HashMap<Node, Integer> vis = new HashMap<>();
s.push(node);
while (!s.isEmpty()) {
vis.put(s.peek(), 1 );
if (s.peek().left != null ) {
if (vis.get(s.peek().left) == null || vis.get(s.peek().left) == 0 ) {
s.push(s.peek().left);
continue ;
}
}
if (s.peek().right != null ) {
if (vis.get(s.peek().right) == null || vis.get(s.peek().right) == 0 ) {
s.push(s.peek().right);
continue ;
}
}
post.add(s.peek().data);
s.pop();
}
return post;
}
public static void main(String[] args) {
String s = "1 2 3 4 5 6 7" ;
Node root = buildTree(s);
List<Integer> ans = postOrder(root);
System.out.println( "Postorder traversal of binary tree is:" );
for ( int i = 0 ; i < ans.size(); i++)
System.out.print(ans.get(i) + " " );
System.out.println();
}
}
|
C#
using System;
using System.Collections.Generic;
public class Node {
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right;
}
}
public class PostOrder {
Node root;
private void postOrderIterative(Node root)
{
Stack<Node> stack = new Stack<Node>();
while ( true ) {
while (root != null ) {
stack.Push(root);
stack.Push(root);
root = root.left;
}
if (stack.Count == 0)
return ;
root = stack.Pop();
if (stack.Count != 0 && stack.Peek() == root)
root = root.right;
else {
Console.Write(root.data + " " );
root = null ;
}
}
}
public static void Main(String[] args)
{
PostOrder tree = new PostOrder();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
Console.WriteLine(
"Post order traversal of binary tree is :" );
tree.postOrderIterative(tree.root);
}
}
|
Javascript
class Node {
constructor(item) {
this .data = item;
this .left = null ;
this .right = null ;
}
}
class PostOrder {
constructor() {
this .root = null ;
}
postOrderIterative(root) {
var stack = [];
while ( true ) {
while (root != null ) {
stack.push(root);
stack.push(root);
root = root.left;
}
if (stack.length == 0) return ;
root = stack.pop();
if (stack.length != 0 && stack[stack.length - 1] == root)
root = root.right;
else {
console.log(root.data + " " );
root = null ;
}
}
}
}
var tree = new PostOrder();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
console.log( "Post order traversal of binary tree is :<br>" );
tree.postOrderIterative(tree.root);
|
Python3
class Node:
def __init__( self , x):
self .data = x
self .right = None
self .left = None
def postOrderIterative(root):
stack = []
while ( True ):
while (root ! = None ):
stack.append(root)
stack.append(root)
root = root.left
if ( len (stack) = = 0 ):
return
root = stack.pop()
if ( len (stack) > 0 and stack[ - 1 ] = = root):
root = root.right
else :
print (root.data, end = " " )
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 )
root.right.left = Node( 6 )
root.right.right = Node( 7 )
print ( "Post order traversal of binary tree is :" )
postOrderIterative(root)
|
Output
Post order traversal of binary tree is :
4 5 2 6 7 3 1
Time complexity: O(n) where n is no of nodes in a binary tree
Auxiliary Space: O(n)
Method 4:
- In this method, the node is only pushed once.Â
- Travel to the extreme left using a loop until null.Â
- Then loop again with the right of the top element of the stack(if it exists). The loop used for traversing to the extreme left is only used in this step in future.Â
- If the right node is null, then pop until that sub-branch is popped from the stack(to avoid an infinite loop of continuously adding and popping the same thing).
The reason why this program works is that after traversing to extreme left in the beginning, further the program has two paths of execution. One is when the right node is given the control and the other is when the right node hits null. When the right node is given the control, just traverse to the extreme left. If null is hit, pop till that sub branch is eliminated from the stack. So a boolean variable is used so that when right node is given control, it sets to true and program changes to travel extreme left mode and other cases just keep on popping.
C++
#include <bits/stdc++.h>
using namespace std;
#define MAX_HEIGHT 100000
struct Node {
int data;
Node* left;
Node* right;
};
Node* newNode( int val)
{
Node* temp = new Node;
temp->data = val;
temp->left = NULL;
temp->right = NULL;
return temp;
}
Node* buildTree(string str)
{
if (str.length() == 0 || str[0] == 'N' )
return NULL;
vector<string> ip;
istringstream iss(str);
for (string str; iss >> str;)
ip.push_back(str);
Node* root = newNode(stoi(ip[0]));
queue<Node*> queue;
queue.push(root);
int i = 1;
while (!queue.empty() && i < ip.size()) {
Node* currNode = queue.front();
queue.pop();
string currVal = ip[i];
if (currVal != "N" ) {
currNode->left = newNode(stoi(currVal));
queue.push(currNode->left);
}
i++;
if (i >= ip.size())
break ;
currVal = ip[i];
if (currVal != "N" ) {
currNode->right = newNode(stoi(currVal));
queue.push(currNode->right);
}
i++;
}
return root;
}
vector< int > postOrder(Node* node)
{
stack<Node*> s;
vector< int > post;
unordered_map<Node*, int > vis;
s.push(node);
while (!s.empty()) {
vis[s.top()] = 1;
if (s.top()->left != 0) {
if (!vis[s.top()->left]) {
s.push(s.top()->left);
continue ;
}
}
if (s.top()->right != 0) {
if (!vis[s.top()->right]) {
s.push(s.top()->right);
continue ;
}
}
post.push_back(s.top()->data);
s.pop();
}
return post;
}
int main()
{
string s = "1 2 3 4 5 6 7" ;
Node* root = buildTree(s);
vector< int > ans;
ans = postOrder(root);
cout << "Post order traversal of binary tree is :\n" ;
for ( int i = 0; i < ans.size(); i++)
cout << ans[i] << " " ;
cout << endl;
return 0;
}
|
Java
import java.util.Arrays;
import java.util.Stack;
public class GFG {
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 );
postorder_iterative(root);
}
public static void postorder_iterative(Node root){
Stack<Node> s = new Stack<>();
boolean check = true ;
while ( true ){
while (root != null && check){
s.push(root);
root = root.left;
}
if (s.empty()) break ;
if (root != s.peek().right){
root = s.peek().right;
check = true ;
continue ;
}
root = s.pop();
System.out.print(root.value + " " );
check = false ;
}
}
}
class Node{
int value;
Node left, right;
public Node( int value){
this .value = value;
left = right = null ;
}
}
|
Python
class Node:
def __init__( self , x):
self .data = x
self .right = None
self .left = None
def postOrderIterative(root):
stack = []
check = True
while ( True ):
while (root ! = None ):
stack.append(root)
root = root.left
if ( len (stack) = = 0 ):
return
if (root ! = stack[ - 1 ].right):
root = stack[ - 1 ].right
check = True
continue
root = stack.pop()
print (root.data, end = " " )
check = False
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 :" )
postOrderIterative(root)
|
C#
using System;
using System.Collections.Generic;
public class Node {
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right;
}
}
public class PostOrder {
Node root;
private void postOrderIterative(Node root)
{
Stack<Node> stack = new Stack<Node>();
bool check = true ;
while ( true ) {
while (root != null && check) {
stack.Push(root);
root = root.left;
}
if (stack.Count == 0)
return ;
if (root != stack.Peek().right) {
root = stack.Peek().right;
check = true ;
continue ;
}
root = stack.Pop();
Console.Write(root.data + " " );
check = false ;
}
}
public static void Main(String[] args)
{
PostOrder tree = new PostOrder();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
Console.WriteLine(
"Post order traversal of the binary tree is :" );
tree.postOrderIterative(tree.root);
}
}
|
Javascript
class Node {
constructor(item) {
this .data = item;
this .left = null ;
this .right = null ;
}
}
class PostOrder {
constructor() {
this .root = null ;
}
postOrderIterative(root) {
var stack = [];
while ( true ) {
while (root != null ) {
stack.push(root);
stack.push(root);
root = root.left;
}
if (stack.length == 0) return ;
root = stack.pop();
if (stack.length != 0 && stack[stack.length - 1] == root)
root = root.right;
else {
console.log(root.data + " " );
root = null ;
}
}
}
}
var tree = new PostOrder();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
console.log( "Post order traversal of binary tree is :<br>" );
tree.postOrderIterative(tree.root);
|
Output
Post order traversal of binary tree is :
4 5 2 6 7 3 1
Time Complexity: O(n), n is the number of nodes of the tree.
Auxiliary Space: O(n), extra stack space is used.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...