Friday, May 1, 2015

Convert Left subtree into right subtree and right into left in tree C++ code: ~ BST

Convert Left Sub Tree of a Root into Right Sub Tree and Right sub Tree into Left Sub 
Tree ☺ ☻


#include<iostream.h>
#include<conio.h>
class Node{
private:
int data;
Node* right,*q,*p;
Node* left;
public:
Node(){
root=NULL;
right=left=NULL;
}Node *root;


void insert(int data){
Node* newnode = new Node();
newnode->data = data;
if (root == NULL){
root=newnode;
return;
}
Node *p,*q;
p=q=root;
while (q!=NULL){
p=q;
if (newnode->data> q->data)
q = q->right;
else q = q->left;
}
if (newnode->data> p->data)
p->right = newnode;
else p->left = newnode;
}




void inorder(Node *root){
if (root == NULL) return;
else {
inorder(root->left);
cout << root->data <<"  ";
inorder(root->right);
}
}

void preorder(Node *root){
if (root == NULL) return;
else {
cout << root->data <<"  ";
preorder(root->left);
preorder(root->right);
}
}

void postorder(Node *root){
if (root == NULL) return;
else {
postorder(root->left);
postorder(root->right);
cout << root->data <<"  ";
}
}
//Function is used to join left sub tree on right side of root
//and right sub tree on left side of root
void exchange(){
Node *temp=root->left;
root->left=root->right;
root->right=temp;
}


};

void main()
{
int c,A[]={9,4,3,2,5,6,8,1,33,12,44};
Node b;
clrscr();
for(int i=0;i<=10;i++){
b.insert(A[i]); }
cout<<"\n\nInorder triversal: ";
b.inorder(b.root);
cout<<"\n\nPreorder triversal: ";
b.preorder(b.root);
cout<<"\n\nPostorder triversal: ";
b.postorder(b.root);
cout<<"\n\n----------+--------------+---------------------+-------------\n\n";
cout<<"\n\nPress Enter to see result after exchanging right subtree with left subtree\n\n";
getch();
b.exchange();
cout<<"\n\nInorder triversal: ";
b.inorder(b.root);
cout<<"\n\nPreorder triversal: ";
b.preorder(b.root);
cout<<"\n\nPostorder triversal: ";
b.postorder(b.root);
getch();


}



Share this

0 Comment to "Convert Left subtree into right subtree and right into left in tree C++ code: ~ BST"