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 ;
}
}
}
}
---------------------------------------------------------------------------------
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
Post a Comment