I am trying to implement the insertion subroutine in a binary search tree, each of whose nodes has a word(string) as key. I'm taking the words from STDIN and inserting them using the insert function. But whenever I take a inorder traversal, I find out that the tree is not growing beyond 3 nodes. What can be wrong? My code is attached here:
typedef struct treenode
{
char word[20]; //word is the key for each node
struct treenode *left;
struct treenode *right;
} treenode;
treenode *insert (treenode *node, char *word)
{
if(node==NULL) //if a null node is reached,make a temp node and append it
{
treenode *temp;
temp = (treenode *) malloc(sizeof(treenode));
strcpy (temp ->word,word);
temp-> left = NULL;
temp-> right = NULL;
return temp;
}
if ((strcmp(word, node ->word)>0)) //if the key is greater than node.word,go to right child
{
node-> right = insert(node-> right, word);
}
else if(strcmp(word,node->word)<=0) //if key <node.word,go to left child
{
node-> left = insert(node-> left, word);
}
}
void printinorder(treenode *node)
{
if(node == NULL) return;
printinorder(node-> left);
printf("%s ",node-> word);
printinorder(node-> right);
}
int main()
{
treenode *root = NULL;
char string[20];
scanf("%s",string); //first input is taken once here and once again inside loop,but its OK
root = insert(root, string+1); //duplicate entries are also stored
while(strcmp(string,".")!=0) //input is terminated by a full stop
{
insert(root, string+1);
scanf("%s",string);
}
printinorder(root); //finally printing the BST
return 0;
}