Morris traversal for Preorder

PROBLEM :

Using Morris Traversal, we can traverse the tree without using stack and recursion


Preorder traversal : 6 3 1 5 8 7 11 9 13

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;---------------------------------------------*/

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

tree *curr ;

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

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

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

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 )