#include<iostream.h>
#include<conio.h>
class bstree;
class node
{
public:
int data;
node *rlink,*llink;
friend class bstree;
};
class bstree
{
node *root;
public:
bstree()
{
root=NULL;
}
void cre();
void bpre(node*);
void bin(node*);
void bpost(node*);
};
void bstree::cre()
{
node *ptr,*par,*temp;
int val,n,i;
cout<<"\n\t Creation of binary search tree \n";
cout<<"\n\t No.of Nodes";
cin>>n;
cout<<"\n\t Enter Data";
for(i=1;i<=n;i++)
{
cin>>val;
ptr=new node;
ptr->data=val;
ptr->llink=NULL;
ptr->rlink=NULL;
if(root==NULL)
root=ptr;
else
{
par=NULL;
temp=root;
while(temp!=NULL)
{
par=temp;
if(val<temp->data)
temp=temp->llink;
else
temp=temp->rlink;
}
if(val<= par->data)
par->llink=ptr;
else
par->rlink=ptr;
}
}
cout<<"\n \tPreorder\n\t";
bpre(root);
cout<<"NULL";
cout<<"\n\n\n\t PostOrder \n\t";
bpost(root);
cout<<"NULL";
cout<<"\n\n\n Inorder \n\t";
bin(root);
cout<<"NULL";
}
void bstree::bpre(node *temp)
{
if(temp!=NULL)
{
cout<<temp->data<<"-->";
bpre(temp->llink);
bpre(temp->rlink);
}
}
void bstree::bin(node *temp)
{
if(temp!=NULL)
{
bin(temp->llink);
cout<<temp->data<<"-->";
bin(temp->rlink);
}
}
void bstree::bpost(node *temp)
{
if(temp!=NULL)
{
bpost(temp->llink);
bpost(temp->rlink);
cout<<temp->data<<"-->";
}
}
void main()
{
bstree b;
b.cre();
getch();
}
Comments
Post a Comment