Hello, having a bit of trouble with this. I am writing a program which sorts a sequence of numbers using a binary tree however i cannot to seem to get it to work; i belive it is something to do with passing the digits to makenode(). Any help would be greatly appreciated. Cheers
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLEN 100
#define IN 1 /*in a number */
#define OUT 0 /*out of a number (whitespace)*/
typedef struct tnode * treeptr; /*pointer to a treenode*/
typedef struct tnode{
char *number;
treeptr left;
treeptr right;
}treenode;
treeptr tmalloc(void);
treeptr makenode(treeptr, char *);
void printtree(treeptr);
int main()
{
int c,k,i = 0;
int status = IN;
char n[MAXLEN];
treeptr root = NULL;
while((c=getchar()) != EOF && c != '\n' && status == IN){
n[i++] = c;
if(c == ' '){
status == OUT;
}
if(c == '\n'){
n[i++] = c;
}
}
n[i] = '\0';
root = makenode(root, n);
printtree(root);
return 0;
}
treeptr tmalloc(void)
{
return (treeptr) malloc((sizeof(treenode))); /*returns a pointer a 'vacant' treenode*/
}
treeptr makenode(treeptr p, char *w) /*creates a new node*/
{
int cond;
if(p == NULL){ /*new number arrived*/
p = tmalloc();
p->number = strdup(w);
p->left = p->right = NULL;
}
else if((cond = strcmp(w, p->number) < 0)){
p->left = makenode(p->left, w); /*assign to left branch if less than the parent node number*/
}
else{
p->right = makenode(p->right, w);/*else assign it to the right if it is greater or equal to*/
}
return p;
}
void printtree(treeptr s) /*prints contents of tree*/
{
if(s != NULL){
printtree(s->right);
printf("%s\n", s->number);
printtree(s->left);
}
}