/* C++ program for Binary Search Tree */
#include <iostream>
#include<cstdlib>
using namespace std;
class node
{
public: int info;
node *left,*right;
friend class BST;
};
class BST
{
public: node *getnode();
node *create_bst_rec(node*,int);
void postorder(node*);
void preorder(node*);
void inorder(node*);
};
node *BST :: getnode()
{
node *p;
p=new node;
p->left=NULL;
p->right=NULL;
return(p);
}
node *BST :: create_bst_rec(node *t,int item)
{
node *q;
if(t==NULL)
{
q=getnode();
q->info=item;
t=q;
}
else
{
if(t->info==item)
{
cout<<"\n ITEM IS ALREADY EXIST...";
return(t);
}
else if(t->info>item)
t->left=create_bst_rec(t->left,item);
else
t->right=create_bst_rec(t->right,item);
}
return(t);
}
void BST :: postorder(node *t)
{
if(t->left!=NULL)
postorder(t->left);
if(t->right!=NULL)
postorder(t->right);
cout<<"\t"<<t->info<<" ";
}
void BST :: preorder(node *t)
{
cout<<"\t"<<t->info<<" ";
if(t->left!=NULL)
preorder(t->left);
if(t->right!=NULL)
preorder(t->right);
}
void BST :: inorder(node *t)
{
if(t->left!=NULL)
inorder(t->left);
cout<<"\t"<<t->info<<" ";
if(t->right!=NULL)
inorder(t->right);
}
int main()
{
BST obj;
node *n1=NULL;
while(1)
{
cout<<"\n1.CREATE\n2.POSTORDER\n3.PREORDER\n4.INORDER\n5.EXIT";
cout<<"\n Enter your choice:";
int ch;
cin>>ch;
switch(ch)
{
case 1:cout<<"\n Enter data to insert: ";
int data;
cin>>data;
n1=obj.create_bst_rec(n1,data);
break;
case 2:obj.postorder(n1);
break;
case 3:obj.preorder(n1);
break;
case 4:obj.inorder(n1);
break;
case 5:exit(0);
default:cout<<"\n wrong choice given";
}
}
return(0);
}
No comments:
Post a Comment