【发布时间】:2012-10-22 16:53:24
【问题描述】:
我正在尝试在 C 中实现二叉搜索树数据结构,但我遇到了一个错误。我的指针值因我不明白的原因而改变。 (请参阅帖子底部的奇怪输出[删除功能和主要功能澄清输出来自哪里]) 我的测试功能如下:
int main(void)
{
Bst *bst = ( Bst* ) calloc( 1, sizeof( Bst ) );
BstInsert( bst, 7 );
BstInsert( bst, 8 );
BstInsert( bst, 2 );
BstInsert( bst, 1 );
BstTraverse( bst );
BstRemove( bst, 7);
printf("=========================\n");
printf("Root Key: %d\n", bst->key );
printf("Left Key: %d\n", bst->left->key );
printf("Right Key: %d\n", bst->right->key );
printf("Location: %p\n", &bst);
BstTraverse( bst );
return 0;
}
我的删除节点功能如下:
void BstRemove( Bst *root, int key ){
//Seems like recursive algorithm would need doubly linked bst implementation
Bst *temp_node = BstFind( root, key );
Bst *parent_node = BstGetParent( root, key );
Bst *replacement_node = ( Bst* ) calloc( 1, sizeof( Bst ) );
if ( temp_node->key == root->key )
{
if (root->left) replacement_node = BstMax( root->left );
else if ( root->right ) replacement_node = BstMin( root->right );
else replacement_node = NULL;
}
else if ( temp_node->left )
{
replacement_node = BstMax( temp_node );
Bst *parent_replacement_node = BstGetParent( root, replacement_node->key );
parent_replacement_node->right = NULL;
}
else if ( temp_node->right )
{
replacement_node = BstMin( temp_node );
Bst *parent_replacement_node = BstGetParent( root, replacement_node->key );
parent_replacement_node->left = NULL;
}
else
replacement_node = NULL;
if ( parent_node && key < parent_node->key )
parent_node->left = replacement_node;
else if ( parent_node )
parent_node->right = replacement_node;
if ( replacement_node )
{
if ( root->left->key != replacement_node->key ) replacement_node->left = temp_node->left;
if ( root->right->key != replacement_node->key ) replacement_node->right = temp_node->right;
}
root = replacement_node;
printf("Root Key: %d\n", root->key );
printf("Left Key: %d\n", root->left->key );
printf("Right Key: %d\n", root->right->key );
printf("Location: %p\n", &root);
free(temp_node);
}
下面的输出:
1
2
7
8
Root Key: 2
Left Key: 1
Right Key: 8
Location: 0x7fffc5cf52e8
=========================
Root Key: 0
Left Key: 2
Right Key: 8
Location: 0x7fffc5cf5338
1
2
8
0
8
这让我如此困惑的原因是因为我使用的是指针。我认为 root-> 键值在删除函数中为 2 时没有理由改变,并且一旦被处理
root->key 变为 0。我感谢任何能指出我的问题或帮助我朝正确方向前进的人。如有必要,您可以在 https://github.com/PuffNotes/C/blob/master/data_structures/binary_tree.c 查看我当前的 BST 实现。我最近开始尝试每天编程以获取一些技能,并认为自己是 C 的初学者(供参考)。谢谢。
【问题讨论】:
-
老实说,我不确定有什么区别,除了 calloc 明确表示我只为一个元素存储内存。只为一个元素分配堆空间并为多个元素分配 calloc 时使用 malloc 是否约定?编辑:对不起,我认为我覆盖了某人的评论而不是评论,他的问题是,你为什么使用 calloc 而不是 malloc?
-
fwiw malloc 和 calloc 的区别在于 calloc 将所有分配的空间设置为 0,而 malloc 不提供任何关于分配内存内容的保证
-
这听起来很奇怪,但请忍耐一下:您是否在您的 Bst 树中初始化 insert 是利用您在程序的第一行分配的空根节点,还是根据比较结果,它会立即开始向左或向右插入。如果你不明白我为什么要问,我会在后面给出猜测的答案。
-
我正在利用根节点来初始化它。我的 BstInsert 函数的前两行是 if( !root->key ) root->key = key;如果有人喜欢的话,我也会在 pastebin 上发布产生这个问题的代码。 pastebin.com/CjCmyBWK
-
老实说,除了您所看到的之外,还有很多其他问题。首先在
if... else逻辑中使用大括号,尤其是在BstInsert中,并且考虑到0是一个神奇的无效整数值(!root-key)也是你应该重新考虑的事情。
标签: c pointers binary-search-tree