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;

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);
	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*/
		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){
		printf("%s\n", s->number);
9 Years
Discussion Span
Last Post by lecotti

1.You're not creating the string properly. status==OUT.
2. If you make the string properly then also the makenode function is not correct, you need to pass the characters of the string one by one, not the whole string at a time. In your case there are no left and right subtrees getting created.
3. Why do you need to create a string by the way. Simply input all the integers and make a tree from that. I mean make a BST from the array, then do inorder traversal, it will sort the list.
4. There is no need to cast malloc, It returns void *.


Hi, thanks for reply. I have sort of semi solved my probelm; i don't undrstand what you mean by "not creating the string properly", could you explain?


1.You're not creating the string properly. status==OUT.

Ahh i see what you mean now, how would i go about creating a routine that would allow me to enter double digits into elements of the array?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.