我正在尝试编写一个程序,将带有成员字符串的节点插入到 BST 中,然后打印有关该 BST 的信息,例如高度、中序遍历、叶子数等...
截至目前,当我进行中序遍历时,它会打印作为根输入的最后一个字符串,即使它应该位于树的底部。
这是代码:
插入功能:
void insert_node(Node* root, char *nextString) {
int newLessThanRoot = strcmp( root->Word, nextString ) > 0 ? 1 : 0; // test if nextString is left or right from root
if (newLessThanRoot && root->Left != NULL) {
return insert_node(root->Left, nextString);
}
if (!newLessThanRoot && root->Right != NULL) {
return insert_node(root->Right, nextString);
}
Node* freshNode = newNode();
freshNode->Word = malloc(strlen(nextString) +1);
strcpy(freshNode->Word, nextString);
freshNode->Left = NULL;
freshNode->Right = NULL;
if (newLessThanRoot) {
root->Left = freshNode;
}
else {
root->Right = freshNode;
}
}
中序遍历函数:
void inorder(Node *temp) {
if (temp != NULL) {
inorder(temp->Left);
printf("%s ",temp->Word);
inorder(temp->Right);
}
}
它们的使用方式:
char inputString[15];
char *inputStringPtr = &inputString[0];
Node* root;
root = newNode();
fscanf(infile,"%s",inputStringPtr);
root->Word = inputString;
//printf("Root's word: %s\n",root->Word);
while (fscanf(infile,"%s",inputStringPtr) == 1) {
insert_node(root,inputStringPtr);
printf("%s\n",inputString);
}
int numberOfStrings = num_of_strings(root);
int heightOfBST = height_of_tree(root);
int numberOfLeaves = num_of_leaves(root);
inorder(root);
输入如下所示:
b a c e d l m n o p z
所以输出(在进行中序遍历时)应该是:
a b c d e l m n o p z
但它是:
z a c d e l m n o p z