Tuesday, January 19, 2010

BINARY TREE

#include
#include
#include
#include
#include

struct node
{
int data;
node *lftchild,*rtchild;
}*root,*temp,*t,*save;

void search(node *,int);
void print(node *);

void main()
{
clrscr();
root=0;
int ch=0;
char c;
while(ch==0)
{
cout< cout< cout< cout< cout< cin>>ch;
switch(ch)
{
case 1:
{
int item;
int found;
do
{
temp=(node *)malloc(sizeof (node));
cout< cin>>item;
temp->data=item;
found=0; //found is false
save=0;
t=root;
while(t!=0 && found==0)
{
save=t;
if(item==t->data)
found=1;
else
{
if(itemdata)
t=t->lftchild;
else
t=t->rtchild;
}
}
if(found==1) //found is true
cout<<"item is already in the tree"< else
{
if(save==0)
{
root=temp;
root->lftchild=0;
root->rtchild=0;
}
else
{
if(itemdata)
save->lftchild=temp;
else
save->rtchild=temp;
}
}
cout<<"do you want to insert again(y/n)::";
cin>>c;
}while(c=='y' || c=='Y');
if(c=='n' || c=='N')
{
ch=0;
break;
}
}

case 2:
{
int element;
cout< cin>>element;
do
{
search(root,element);
cout< cin>>c;
}while(c=='y' || c=='Y');
if(c=='n' || c=='N')
{
ch=0;
break;
}
}

case 3:
{
if(root==0)
{
cout<<"there is no element in the tree"< ch=0;
break;
}
else
{
t=root;
print(t);
}
ch=0;
break;
}

case 4:
{
ch=4;
exit(0);
}
}
}
getch();
}

void print(node *t)
{
if(t!=0)
{
print(t->lftchild);
cout<data;
print(t->rtchild);
}
}

void search(node *t,int element)
{
if(t==0)
cout<<"there is no element in the tree"< else
{
if(t->data==element)
cout<<"item found"< else
{
if(elementdata)
search(t->lftchild,element);
else
search(t->rtchild,element);
}
}
}

No comments: