0
我試圖在二叉搜索樹中實現插入子例程,其中每個節點都有一個字(字符串)作爲鍵。 我從STDIN中取詞並使用插入功能插入它們。但是每當我進行遍歷時,我都會發現樹不會超過3個節點。什麼可能是錯誤的?我的代碼是在這裏附:樹不會超出大小3
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;
}
你可能想要回到這個東西的底部。並[避免在C程序中投射malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 – WhozCraig 2014-10-11 05:48:28
嘗試調試器並查看'* insert()'。 – user1336087 2014-10-11 05:49:03
@WhozCraig謝謝,返回工作。 – 2014-10-11 06:06:31