17 Nov 2013

Inorder Traversal using Stack

Problem Statement:
                 Implement In-order traversal using Stack for given Binary Tree.

Fig1: Given Binary Tree

Resultant Inorder Traversal using Stack , (with Space O(n))

Fig2: The in-order traversal of the given Binary Tree

Solution:

Full Source Code: LINK


 -/**
 *Inorder Traversal using Stack 
 * @author Prateek
 */

 public void inorderTravese(Node root) {

  if (root == null)
   return;
  Stack<Node> stack = new Stack<Node>();
  
  Node current= root;
  while (true) {
   if(current!=null)
   {
    stack.push(current);
    current = current.left ;
   }
   else
   {
    if(!stack.isEmpty()){
     Node item = stack.pop() ;
     System.out.print(item + "\t");
     current=item.right;
    }
    else
     break;
   }
  }
 }                          -

 You can also do in-order traverse using recursion and Morris-Traversal using the concept of threaded binary trees.
 
Please comment and post your suggestion if you like the post or any improvisation needed in the code.

Happy Coding !! :)

No comments:

Post a Comment