Here we show a non recursive algorithm to implement inorder traversal of binary tree.
Algorithm
Firstly,root node is the current node.
1.Push the current node on stack and traverse its leftmost subtree.Push visited
nodes on stack.
2.Pop a node from stack and print it.If right child exists for this node make it as
current node.Repeat 1
Code
void inorder(node* curr)
{
int exists = 0;
init(s);
push(curr);
while(!empty())
{
exists = 0;
while(curr->left!=NULL)
{
curr=curr->left;
push(curr);
}
while(!exists && !empty())
{
curr=pop();
printf("%c",curr->data);
if(curr->right!=NULL)
{
curr = curr->right;
push(curr);
exists = 1;
}
}
}
}
Firstly,root node is the current node.
1.Push the current node on stack and traverse its leftmost subtree.Push visited
nodes on stack.
2.Pop a node from stack and print it.If right child exists for this node make it as
current node.Repeat 1
void inorder(node* curr)
{
int exists = 0;
init(s);
push(curr);
while(!empty())
{
exists = 0;
while(curr->left!=NULL)
{
curr=curr->left;
push(curr);
}
while(!exists && !empty())
{
curr=pop();
printf("%c",curr->data);
if(curr->right!=NULL)
{
curr = curr->right;
push(curr);
exists = 1;
}
}
}
}
Exists variable is used to check whether right child of popped node exists.
No comments:
Post a Comment