The following program will store names in a tree and then search a name , entered by the user in the tree.
# include< stdio.h>
# include< stdlib.h>
#include< string.h>
struct node
{
char info[100];
struct node *left;
struct node *right;
};
int flag=0;
int search(struct node *n, char info[100])
{
while (n != NULL)
{
if (strcmp(n->info,info)==0)
{
flag = ++;
}
else
{
if(strcmp(info,n->info)<=0)
n = n->left;
else
n = n->right;
}
}
return(flag);
}
struct node * create()
{
struct node *node;
char info[100];
node=(struct node *)malloc(sizeof(struct node));
fflush(stdin);
printf("\nEnter the name:-");
gets(info);
strcpy(info,strupr(info));
strcpy(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(strcmp(t->info,root->info)<=0)
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("%s,%d (level)", t->info,level);
printf("\n");
output(t->left, level+1);
}
}
void main()
{
int flag,xx=0;
char info[100];
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);
fflush(stdin);
}
printf("\nEnter the value to be searched :-");
gets(info);
strcpy(info,strupr(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