Morris Traversal ( Threaded Binary Tree )

PROBLEM :

Inorder Tree Traversal without recursion and without stack!

Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree.



--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;------------------------------*/


void Morris_tree_traversal(tree *root)
{
if(root==NULL)
return ;

tree *current,*prev ;
current=root ;

while(current!=NULL)
{
if(current->left==NULL)
{
cout<<current->info<<" " ;
current=current->right ;
}
else
{
prev=current->left ;
while(prev->right!=NULL&&prev->right!=current)
prev=prev->right ;

if(prev->right==NULL)
{
prev->right=current ;
current=current->left ;
}
else
{
prev->right=NULL ;
cout<<current->info<<" " ;
current=current->right ;
}
}
}
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )