Monday, May 6, 2013

Iterative code for Inorder Traversal in C - Binary Tree

Iterative code for inorder traversal uses Stack to print the tree in inorder. The idea behind this code is to push the elements into stack , popping and printing it . 

Steps are given below 

     1. Get the root element and left side children and push it into stack .
     2. Pop the element from stack , print it and check whether is has right child or not . If it has push right child and its left children into stack . 
     3. Continue step 2 until there is no element in stack . 


For the above diagram inorder traversal is 

1 2 3 4 5 6 7 

Code :(in C)
void inorderTraversal(struct node *root)
{
if(root==null)
return null;
struct node *temp=root,temp1;
while(true)
{
while(temp!=null)
{
push(temp);
temp=temp->left;
}
temp1=pop();
if(temp1==null)
break;
printf("%d ",temp1->data);
if(temp1->right!=null)
temp=temp1->right;
}
}
view raw inorder.c hosted with ❤ by GitHub

Please let me know if you have any questions . 

1 comment:

Nadav said...

very nice man. finally a simple solution with make-sense variable names!