Algorithm
Make root node as current node.
Until current node is not NULL
a)Print current key.
b)if current node has left child,then make left child as current node.
c)else if current node has right child then make right child as current node.
d)else
Until right thread exists for current node
Traverse up the right threads and update current.
if current node = last node.STOP.
else make right child of current node as current.
Code
void preorder(node* root)
{
node* curr = root;
while(curr!=NULL)
{
printf("%d ",curr->key);
if(curr->left!=NULL)
curr=curr->left;
else if(curr->is_rchild==1)
curr=curr->right;
else
{
while(curr->right!=NULL && curr->is_rchild==0) //right thread exists
curr=curr->right;
if(curr->right == NULL) //last node
break;
else
curr=curr->right;
}
}
}
How to add count in this program if we need to count the no of nodes
ReplyDelete