Wednesday, October 17, 2012

C Data Structure Program on Searching a tree



A common action involving trees is a search for values in a tree.One of the advantages of tree over  linked list is that you can determine whether an element is in a tree in fewer steps than you need to search for an element in a linked list.

# include< stdio.h>
# include< stdlibc.h>
struct node
{
int info;
struct node *left;
struct node *right;
};
int i=0,j=0,flag=0,x=0,y=0;
int search(struct node *n, int info)
{
while (n != NULL)
{
if (n->info == info)
{
flag = 1;
return(flag);
}
else
{
if(info < n->info)
n = n->left;
else
n = n->right;
}
}
return(flag);
}
struct node * create()
{
  struct node *node;
  int info;
  node=(struct node *)malloc(sizeof(struct node));
  fflush(stdin);
  printf("\nEnter the value:-");
  scanf("%d",&info);
  node->info=info;
  node->left=NULL;
  node->right=NULL;
  return node;
}
struct node *add(struct node *t,struct node *root)
{
 if(root==NULL)
   {
   root=t;
   return root;
   }
   if(t->info<=root->info)
      root->left=add(t,root->left);
   else
    root->right=add(t,root->right);
     return root;
 }
void  output(struct node *t, int level)
{
int i;
if (t)
{
 output(t->right, level+1);
  printf("\n");
for (i = 0; i < level; i++)
printf("   ");
printf("%d,%d (level)", t->info,level);
printf("\n");
 output(t->left, level+1);
}
}
void main()
{
int flag, info, xx=0;
char choice='y';
struct node *t,*root=NULL,*rr;
clrscr();
 while(choice != 'n')
{
 t=create ();
if(xx==0)
 rr=t;
xx++;
printf("\n Tree is ");
root=add(t,root);
output(rr,0);
fflush(stdin);
printf("\n Enter choice--'n' to break:");
scanf("%c",&choice);
}
printf("\nEnter the value to be searched :-");
scanf("%d",&info);
flag = search(rr, info);
if (flag)
printf("\n Element is available in the tree. \n");
else
printf("Element is not avaible in the tree.");
getch();
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner