13 Apr 2014

Trees: Iterative Post-order traversal using two stacks

Problem Statement:
       Perform post-order traversal using two stacks for the given binary tree.


Output: 
Post-order :  8 , 4 , 5 , 2 , 6 , 9 , 7 , 3 , 1

Solution:
Download Source Code

By post-order traversal I mean , process the Left Node ,then Right Node, and then Node all this processing happens in Depth First Search fashion. I assume that you know the recursive way to iterate a binary tree.

Pre-order Traversal : Node, Left Node, Right Node   -  +AB
In-order Traversal : Left Node, Node , Right Node      -  A+B
Post-order Traversal: Left Node, Right Node, Node   -  AB+

Iterative Traversal can also be done by Morris traversal , which uses the concept of Threaded Binary Trees.
Here we are performing iteration using two Stacks, also refer to my post using single stack.

Below is the implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
  * Iterative Pre-order traversal using two stacks 
  */
 public void iterativePostOrder(Node root)
 {
   Stack<Node> processed = new Stack<Node>();
   Stack<Node> current = new Stack<Node>();
   
   current.push(root);
   while(!current.isEmpty())
   {
    Node item = current.pop();
    processed.push(item);
    
    if(item.left!=null)
    current.push(item.left);
    if(item.right!=null)
    current.push(item.right);
    
   }
   while(!processed.isEmpty())
   {
    System.out.print(processed.pop() + "\t");
   }
 }

Please post your suggestions and comments.
Happy Coding !! :)

No comments:

Post a Comment