I am working on a binary tree. And was wondering what is the best way to traverse it(I want to print it) also does anyone see anything wrong with this. It looks fine to me(besides checking the return value of fgets and ssanf?
Code:
struct info{
int x;
struct info *less;
struct info *more;
};
void add_number(void){
static struct info *head;
int x;
char buffer[BUFSIZ];
if(!head){
head=malloc(sizeof(struct info));
if(!head){
printf("Out of Memory\n");
exit(1);
}
printf("Enter a number\n");
fgets(buffer,sizeof buffer,stdin);
sscanf(buffer,"%d",&x);
head->x=x;
}
else{
printf("Enter a number\n");
fgets(buffer,sizeof buffer,stdin);
sscanf(buffer,"%d",&x);
if(x>head->x){
head->more=malloc(sizeof(struct info));
if(!head->more){
printf("Out of Memory\n");
exit(1);
}
head->more->x=x;
head=head->more; /*is this a good idea*/
}
else if(x<head->x){
head->less=malloc(sizeof(struct info));
if(!head->less){
printf("Out of Memory\n");
exit(1);
}
head->less->x=x;
head=head->less; /*same here*/
}
else
printf("Equal number as before disregaurding\n");
}
}