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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Please let me know if you have any questions .
1 comment:
very nice man. finally a simple solution with make-sense variable names!
Post a Comment