【发布时间】:2019-11-05 09:54:13
【问题描述】:
我正在尝试将 4 个名称插入 bst。我有打印语句,说明名称在树上的哪个位置通过,然后当名称找到有效位置时输出“null”的打印语句。例如:
如果根是 Dennis,下一个要插入的节点是 Armin,则打印
左 空
但是,当我尝试按顺序打印树时,我错过了一个名称。
我尝试手动打印出节点,就像 printf("%s", node->data);但我只是得到一个分段错误。
我要打印的名字是apple、cris、dennis、loki。但输出是:apple, cris, loki。它总是跳过丹尼斯。
bstNode* insertNode(bstNode *root, char *data){
if(root == NULL){
printf("null, %s\n", data);
root = newNode(data);
return;
}
else if(wordSort(root->data, data) == -1){
printf("right, %s\n", data);
root->right = insertNode(root->right, data);
}
else if(wordSort(root->data, data) == 1){
printf("left, %s\n", data);
root->left = insertNode(root->left, data);
}
}
void printTree(bstNode *node){
//printf("%s\n", node->left->data);
//printf("%s\n", node->data);
//printf("%s\n", node->right->data);
//printf("%s\n", node->right->right->data);
if (node == NULL)
return;
printTree(node->left);
printf("%s\n", node->data);
printTree(node->right);
}
bstNode* newNode(char *data){
bstNode* newnode = (bstNode*)malloc(sizeof(bstNode));
newnode->data = (char*)malloc(100 * sizeof(char));
strcpy(newnode->data, data);
newnode->left = NULL;
newnode->right = NULL;
strcpy(newnode->data, data);
newnode->count = 1;
return newnode;
}
【问题讨论】:
-
函数 bstNode* insertNode(bstNode *root, char *data){ 虽然返回类型为 bstNode *,但什么也不返回。
-
bstNode严重损坏。例如,如果root是NULL,它将调用newNode,将结果分配给局部变量root,然后返回,丢弃新节点并保持调用者的根不变。它已被声明为返回bstNode *,但已被实现为(有缺陷的)void函数。需要修复它以始终返回新的根节点。 -
我目前正在 PuTTY 上运行程序,这就是代码出现故障的地方,但是当我将相同的代码插入在线编译器时,它可以完美运行。任何原因以及无论如何我都可以在 PuTTY 上修复它
-
它可能起作用的唯一方法是调用者碰巧从寄存器中提取了一个杂散值(例如
root),这实际上是正确的返回值。但是你不能依赖这个。这也是一个毫无意义的错误 - 只需修复它。您的编译器应该对此代码给出多个警告。在寻求帮助之前,请务必修复警告。 -
没关系,我明白你的意思,汤姆。我修复了它,它现在可以工作了,非常感谢:)
标签: c recursion memory-management binary-search-tree undefined-behavior