c - 删除二叉树中的一个叶节点

标签 c data-structures binary-search-tree

我正在尝试从二叉搜索树中删除一个叶节点,但它对我不起作用,我调试了代码,但找不到问题。我可以看到流程正确,调用到达 leaf node 地址,然后调用 free。但在那之后,当我执行 pre-order 遍历时,我看到值仍然存在。

我创建的二叉树(很简单)-:

                           10
                         /    \
                        6      14

Leaf Node 要删除的值 = 14;

删除前Pre-order遍历结果=10->6->14。这打印在我的控制台上。

删除叶节点的代码-:

// Delete a leaf node

void deleteNode(struct Nodes * root,int value){

    // Check if root is null

    if (root == NULL) {
        return;
    }

    // If no left and right node present, it's a leaf node. Perform delete.

    while (root->left == NULL && root->right == NULL) {

        // Check if value at leaf node is same as value to be deleted. If yes, go inside (if).

        if (root->info == value) {
            printf("Delete the leaf node \n");

            printf("delete node address is \n %p",root);

            // free the root (which is currently a leaf node)
            free(root);
            return;
        }
    }

    // keep checking if value to be deleted is on right or left, till a value is found.

    if (root->info < value) {
        // Ccheck on right
        deleteNode(root->right,value);
    }else{
        // check on left
        deleteNode(root->left,value);
    }

}

我没有得到任何错误,所以我无法猜测根本原因

删除Pre-order后遍历结果=10->6->14。谁能帮我吗?我知道我犯了非常愚蠢的错误,或者我的概念仍然不清晰。谢谢。

Please let me know if any other information is required.

输出图像-:你可以看到我的值是正确的,地址也是一样的。

enter image description here

最佳答案

free 几乎意味着“我发誓我不会再使用内存,它可能会被释放或任意重新分配”。

您违反了该 promise 。释放内存后,您还必须忘记该地址上的所有引用。父节点还记得该节点曾经所在的地址,碰巧内存还没有被回收。

您有一个典型的“释放后使用”错误。如果您在中间分配了另一个节点,那么在再次遍历之前,您会注意到内存损坏。

您可以在函数中再添加一个参数,该参数指向父对象中的指针。这样您就可以修改父项。

或者将引用存储回节点中的父节点。

都可以。

关于c - 删除二叉树中的一个叶节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47980061/

相关文章:

delphi - 哪个 Delphi 数据结构可以保存唯一整数列表?

c++ - Trie删除不成功

c - 打印 BST 中的 n 个最大值

javascript - 如何存储二叉搜索树的深度

c - sscanf - 读取十六进制值不适用于逗号

c++ - 在不使用静态成员的情况下跨对象树共享数据的策略

c - Linux:捕获已运行进程的输出(纯 C 语言!)

c - 如何在不重新编译Linux内核的情况下实现自己的系统调用?

Python - 定向边列表到字典的字典

c++ - 使用递归的 BST 中序遍历