Two nodes of a BST are swapped, correct the BST

PROBLEM :

Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST.

Input Tree:
         10
        /  \
       5    8
      / \
     2   20

In the above tree, nodes 20 and 8 must be swapped to fix the tree.
Following is the output tree
         10
        /  \
       5    20
      / \
     2   8

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

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

void swap_node_tree(tree **,tree **) ;
void Two_nodes_swap_tree(tree *,tree **,tree **,tree **,tree **) ;

void treeswap2elemets(tree *root)
{
tree *prev,*first,*middle,*last ;
prev=NULL ;
first=NULL ;
last=NULL ;

Two_nodes_swap_tree(root,&prev,&first,&middle,&last) ;
if(last==NULL)
swap_node_tree(&first,&middle) ;
else
swap_node_tree(&first,&last) ;
}

void Two_nodes_swap_tree(tree *root,tree **prev,tree **first,tree **middle,tree **last)
{
if(root==NULL)
return ;

Two_nodes_swap_tree(root->left,&(*prev),&(*first),&(*middle),&(*last)) ;
if((*prev)!=NULL)
{
if(root->info<(*prev)->info)
{
if((*first)==NULL)
{
(*first)=(*prev) ;
(*middle)=root ;
}
else
(*last)=root ;
}
}
(*prev)=root ;
Two_nodes_swap_tree(root->right,&(*prev),&(*first),&(*middle),&(*last)) ;
}

void swap_node_tree(tree **first,tree **second)
{
int temp ;

temp=(*first)->info ;
(*first)->info=(*second)->info ;
(*second)->info=temp ;
}


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

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 )