Solution #1: We can use a stack to implement Inorder traversal without recursion. Here is the code,
void recInorder(struct node* root, stack& s) { struct node* current = root; while(1) { if(current != NULL) { s.push(current); current = current->left; } else { if(!s.empty()) { struct node* temp = s.top(); s.pop(); printf("%d ", temp->data); current = temp->right; } else break; } } printf("\n"); }
1 comment:
This is in C++:No Stack!!
void InOrder(Node *r)
{
if(r==NULL)
return;
Node *t=r;
while(t!=NULL)
t=t->left;
while(t!=r)
{
if(t==(t->parent->left))
{
cout<parent->data;
t=t->parent->right;
if(t!=NULL)
{
while(t!=NULL)
t=t->left;
}
if(t==NULL)
t=t->parent;
}
if(t==t->parent->right)
{
t=t->parent;
}
}
}
Post a Comment