Thanks
Here is my code:
#include <stdlib.h>
#include <stdio.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
}*top,*a,*b;
struct tree *make(int m)
{
struct tree *newnode;
newnode=(struct tree *)malloc(sizeof(struct tree));
newnode->data=m;
newnode->right=newnode->left=NULL;
return(newnode);
}
void left(struct tree *t,int x)
{
if(t->left!=NULL)
printf("\n Invalid!");
else
t->left=make(x);
}
void right(struct tree *t,int x)
{
if(t->right!=NULL)
printf("\n Invalid!");
else
t->right=make(x);
}
void inorder(struct tree *t)
{
if(t!=NULL)
{
inorder(t->left);
printf("\t %d",t->data);
inorder(t->right);
}
}
void locate(struct tree *t, int num)
{
if ( t==NULL )
{
printf("\n The number is NOT found!");
}
else
{
if ( t->data==num )
{ printf("\n --------------------------");
printf("\n The number is found\n");
printf("\n --------------------------");
}
else if ( t->data<num )
locate(t->right,num);
else
locate(t->left,num);
}
}
int main(void)
{
int num, loc;
char ans;
char choice;
printf("\na. Add an integer to the tree\n");
printf("b. List the sorted list of the integers in the tree\n");
printf("c. Find if an integer exists in the tree\n");
printf("d. Exit\n");
scanf("%s", &choice);
switch(choice)
{ case'a':
printf("\n Enter a number: ");
scanf("%d",& num);
top=make(num);
a=top;
do
{
printf("\n\n Add a number?(Y/N): ");
scanf(" %c",&ans);
if ( ans=='y' || ans=='Y' )
{
printf("\n Enter a number: ");
scanf("%d",&num);
if ( num==-1 )
break;
a=top;
b=top;
while ( num!=a->data && b!=NULL )
{
a=b;
if ( num<a->data )
b=a->left;
else
b=a->right;
}
if ( num<a->data )
{
left(a,num);
}
else
{
right(a,num);
}
}
else
{
//How do I get out from here and go thru the switch again???
}
} while ( ans=='y' || ans=='Y' );
scanf("%s",&choice);
case 'b':
printf("\n\nSorted Tree:\n ");
inorder(top);
break;
case 'c':
printf("\n\n Enter the number to locate: ");
scanf("%d",&num);
locate(top,num);
break;
case 'd': exit(0);
break;
}
}

New Topic/Question
Reply




MultiQuote







|