Tuesday, January 19, 2010

DEPTH FIRST SEARCH

#include
#include
#include
#include
#include

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

struct stack
{
node *info;
stack *link;
}*top,*temp1;

void push(node *);
node *pop();

void main()
{
clrscr();
root=0;
int ch=0;
char c;
while(ch==0)
{
cout< cout< cout< cout< cin>>ch;
switch(ch)
{
case 1:
{
int item;
int found;
do
{
temp=(node *)malloc(sizeof (node));
cout< 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"< 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:
{
top=0;
if(root==0)
{
cout< ch=0;
break;
}
push(root);
while(top!=0)
{
xyz=pop();
xyz->status=2;
cout<data<<"\t";
if(xyz->rtchild->status==0)
push(xyz->rtchild);
if(xyz->lftchild->status==0)
push(xyz->lftchild);
}
ch=0;
break;
}

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

void push(node *p)
{
temp1=(stack *)malloc(sizeof(stack));
p->status=1;
temp1->info=p;
temp1->link=top;
top=temp1;
}

node *pop()
{
item=top->info;
top=top->link;
return(item);
}

No comments: