Swap 2 nodes in a Binary tree

PROBLEM :

Swap 2 nodes in a Binary tree.(Tree is BST)

ex:
5
/ \
      3   7
     /  \ /
    2 4 6
Inorder traversal : 2 3 4 5 6 7
swap 7 and 3

5
/  \
       7  3
      /  \  /
      2 4 6
Inorder traversal : 2 7 4 5 6 3

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

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

void swap_node_tree(tree **,tree **) ;
void swap_tree_nodes(tree *,tree **,tree **,int *,int *) ;

void treeswap2elemets(tree *root)
{
int p1,p2 ;
tree *first,*second ;

cout<<"\n enter the position of two elemets that needed to be swaped" ;
cin>>p1 ;
cin>>p2 ;
swap_tree_nodes(root,&first,&second,&p1,&p2) ;
swap_node_tree(&first,&second) ;
}

void swap_tree_nodes(tree *root,tree **first,tree **second,int *p1,int *p2)
{
if(root==NULL)
return ;

swap_tree_nodes(root->left,&(*first),&(*second),&(*p1),&(*p2)) ;

if((*p1)==1)
(*first)=root ;
if((*p2)==1)
(*second)=root ;

(*p1)-- ;
(*p2)-- ;

swap_tree_nodes(root->right,&(*first),&(*second),&(*p1),&(*p2)) ;
}

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

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


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

Comments