/* Binary Search Tree
Roll no:- 09BCE006
*/
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<process.h>
struct tree
{
int info;
struct tree *lptr,*rptr;
}*root,*head,*hroot;
void insert(struct tree*,int);
void del(struct tree*,int);
void inorder(struct tree*);
void preorder(struct tree*);
void postorder(struct tree*);
void main()
{
clrscr();
int ch,x;
char cho;
while(1)
{
cout<<"\n\n1.INSERTION\n2.INORDER TRAVERSAL\n3.PREORDER TRAVERSAL\n";
cout<<"4.POSTORDER TRAVERSAL\n5.DELETION\n6.EXIT\n";
cout<<"Enter ur choice\n";
cin>>ch;
clrscr();
switch(ch)
{
case 1:cout<<"Enter ur value whiich is to be inserted\n";
cin>>x;
insert(hroot,x);
break;
case 2:inorder(hroot);
break;
case 3:preorder(hroot);
break;
case 4:postorder(hroot);
break;
case 5:cout<<"enter the value";
cin>>x;
del(hroot,x);
break;
case 6:exit(1);
}
}
getch();
}
void insert(tree *root,int x)
{
tree *temp;
temp=new tree;
temp->info=x;
temp->lptr=NULL;
temp->rptr=NULL;
if(root==NULL)
{ hroot=root=temp;
}
else
{if(root->info<temp->info)
{
if(root->rptr==NULL)
{
root->rptr=temp;
}
else
{
root=root->rptr;
insert(root,x);
}
}
else
{
if(root->lptr==NULL)
{
root->lptr=temp;
}
else
{
root=root->lptr;
insert(root,x);
}
}
}
}
void inorder(tree *root)
{
if(root==NULL)
{
cout<<"\n TREE IS EMPTY\n";
exit(0);
}
if(root->lptr!=NULL)
{
inorder(root->lptr);
}
cout<<endl<<root->info;
if(root->rptr!=NULL)
{
inorder(root->rptr);
}
return;
}
void preorder(tree *root)
{
if(root==NULL)
{
cout<<"\n TREE IS EMPTY\n";
exit(0);
}
else
{
cout<<endl<<root->info;
}
if(root->lptr!=NULL)
{
preorder(root->lptr);
}
if(root->rptr!=NULL)
{
preorder(root->rptr);
}
return;
}
void postorder(tree *root)
{
if(root==NULL)
{
cout<<"\n TREE IS EMPTY\n";
exit(0);
}
if(root->lptr!=NULL)
{
postorder(root->lptr);
}
if(root->rptr!=NULL)
{
postorder(root->rptr);
}
cout<<endl<<root->info;
return;
}
void del(tree *root,int n)
{
tree *par,*p,*temp;
if(root==NULL)
{
cout<<"tree is empty ";
exit(0);
}
else
{
par=NULL;
p=root;
}
while(p!=NULL)
{
if(n==p->info)
{
break;
}
else if(n<p->info)
{
par=p;
p=p->lptr;
}
else
{
par=p;
p=p->rptr;
}
}
/* if(p->lptr!=NULL && p->rptr!=NULL)
{
par=p;
}*/
if(p->lptr==NULL && p->rptr==NULL)
{
temp=NULL;
}
else if(p->lptr!=NULL && p->rptr==NULL)
{
temp=p->lptr;
}
else if(p->lptr==NULL && p->rptr!=NULL)
{
temp=p->rptr;
}
if(par!=NULL)
{
if(p==par->lptr)
{
par->lptr=temp;
}
else
{
par->rptr=temp;
}
}
else
{
p=temp;
}
}
c language code snippets to learning coding
Bubble sorting c example code