Sunday, 15 April 2018

Binary Search Tree Creation ,Insertion ,all type of show function,Search ,largest & smallest node ,mirror

#include<iostream>
using namespace std;
struct node
{
int data;
node *LC,*RC;
};
class BST
{
public:
node *T,*pointer;
BST();
node* create();
void inorder(node*);
void preorder(node*);
void postorder(node*);
void smallest(node*);
void largest(node*);
void keynode(node*,int);
node* mirror(node *);
};
BST::BST()
{
T=NULL;
}
void BST::inorder(node *ptr)
{
if(ptr!=NULL)
{
inorder(ptr->LC);
cout<<ptr->data<<"-->";
inorder(ptr->RC);
}
}
void BST::preorder(node *p)
{
if(p!=NULL)
{
cout<<p->data<<"-->";
preorder(p->LC);
preorder(p->RC);
}
}
void BST::postorder(node *a)
{
if(a!=NULL)
{
postorder(a->LC);
postorder(a->RC);
cout<<a->data<<"-->";
}
}
void BST::largest(node *b)
{
while(b->RC!=NULL)
{

b=b->RC;
}
cout<<"\nlargest value is :"<<b->data;
b=pointer;

}
void BST::smallest(node *c)
{
while(c->LC!=NULL)
{

c=c->LC;
}
cout<<"\nsmallest value is :"<<c->data;
c=pointer;

}
void BST::keynode(node *root,int x)
{
int depth=0;
node *temp=new node;
temp=root;
while(temp!=NULL)
{

if(x==temp->data)
{

cout<<"\ndata found";
return ;
}
else if(x>temp->data)
temp=temp->RC;
else
temp=temp->LC;
}
cout<<"\nnot found";
return ;
}
node* BST::create()
{
node *p,*q,*r;
int n,i,x;
cout<<"\n\nhow many elements (nodes) do you want to enter :";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"\nenter data:\n";
cin>>x;
r=new node;
r->data=x;
r->LC=NULL;
r->RC=NULL;
if(T==NULL)
T=r;
else
{

p=T;
while(p!=NULL)
{
q=p;
if(x>p->data)
p=p->RC;
else
p=p->LC;
}
if(x>q->data)
q->RC=r;
else
q->LC=r;
}
}
return T;
}
node * BST::mirror(node *r)
{
node *p;
p=r->LC;
r->LC=r->RC;
r->RC=p;
if(r->LC!=NULL)
mirror(r->LC);

if(r->RC!=NULL)
mirror(r->RC);

return r;

}
int main()
{
BST b1;
int n;
node *root;
root=NULL;
cout<<"\n***creation of bst...\n";
root=b1.create();
cout<"\n";
cout<<"Inoreder Traversal.....\n";
b1.inorder(root);
cout<<"\n";
cout<<"Preorder Traversal.....\n";
b1.preorder(root);
cout<<"\n";
cout<<"Postreder Traversal.....\n";
b1.postorder(root);
    b1.largest(root);
    b1.smallest(root);
    cout<<"\nenter key to be searched : \n";
    cin>>n;
    b1.keynode(root,n);
cout<<"\nmirror reflection of bst... :\n";

    root=b1.mirror(root);
    b1.inorder(root); 
return 0;
}

No comments:

Post a Comment