Thursday, January 14, 2010

BREADTH FIRST SEARCH

#include
#include
#include
#include
#include

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

struct queue
{
node *info;
queue *linkback,*linkforward;
}*front,*rear,*temp1;

void insert(node *);
node* remove();

void main()
{
clrscr();
front=0;
rear=0;
root=0;
int ch=0;
char c;
while(ch==0)
{
cout<<<"1:insert into binary search tree"; cout<<<"2:print the elements of the tree"; cout<<<"3:exit"; cout<<<"enter your choice"; cin>>ch;
switch(ch)
{
case 1:
{
int item;
int found;
do
{
temp=(node *)malloc(sizeof (node));
cout<<<"enter the element to be inserted::"; cin>>item;
temp->status=0;
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"<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:
{
// front=0;
if(root==0)
{
cout<<<"tree is empty"<status=2;
cout<data<<"\t"; if(xyz->lftchild->status==0)
insert(xyz->lftchild);
if(xyz->rtchild->status==0)
insert(xyz->rtchild);
}
ch=0;
break;
}

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

void insert(node *p)
{
if(front==0 && rear==0)
{
temp1=(queue *)malloc(sizeof(queue));
p->status=1;
temp1->info=p;
temp1->linkback=0;
temp1->linkforward=0;
front=temp1;
rear=temp1;
}
else
{
temp1=(queue *)malloc(sizeof(queue));
p->status=1;
temp1->info=p;
rear->linkforward=temp1;
temp1->linkback=rear;
rear=temp1;
temp1->linkforward=0;
}
}

node *remove()
{
item=front->info;
front=front->linkforward;
return(item);
}

1 comment:

Anonymous said...

good one lage raho