c++ - 在二进制搜索树中删除节点时 Visual Studio 中的访问冲突异常

标签 c++ tree

运行 BST 删除 时出现异常。 下面是我的代码片段:

Bst::node * Bst::del(node *root, int num)
{
    if (root == NULL)
    {
        return root;
    }
    else if (num < root->data)
    {
        root->left = del(root->left, num);
    }
    else if (num > root->data)
    {
        root->right = del(root->right, num);
    }
    else
    {
        if (root->left == NULL)
        {
            node * tmp = root;
            root = root->right;
            delete tmp;
        }
        else if (root->right == NULL)
        {
            node * tmp = root;
            root = root->left;
            delete tmp;
        }
        else if (root->left == NULL && root->right == NULL)
        {
            delete root;
            root = NULL;
        }
        else
        {
            node *tmp = root;
            tmp = findMin(root->right);
            root->data = tmp->data;
            root->right = del(root->right, tmp->data);
        }
    }


    return root;
}

////////////////////////////////////////////////////////////////////

void Bst::del(int num)
{
    del(root, num);
}

当我删除其他节点时一切正常,但是当我删除根节点本身时,函数 void Bst::del(int num) 从函数 中获取垃圾值Bst::node * Bst::del(node *root, int num).当我将函数重写为

时错误得到解决
  void Bst::del(int num)
        {
            root = del(root, num);
        }

问题 1. 为什么删除中间节点或除根节点以外的任何其他节点时有效。在调试时,我发现当函数 Bst::node * Bst::del(node *root, int num) 正在执行时,甚至 root 也被正确删除,但是当调用返回到 void Bst::del(int num) 然后 root 的值没有得到保留并且是垃圾。

问题二:为什么将返回值保存到变量root中,错误得到修复?

最佳答案

假设你有一个名为 root 的成员变量,那么问题可能是因为你用参数 root 隐藏了成员变量 root你的删除功能。因此,当您在函数中执行 root = NULL 时,您只是将参数设置为 NULL 而不是成员变量。

root 的其他赋值也存在问题,它只会赋值给局部参数而不是成员变量。

我认为您所做的修复(在调用函数中分配给 root)是最正确的解决方案。

关于c++ - 在二进制搜索树中删除节点时 Visual Studio 中的访问冲突异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28066566/

相关文章:

c++ - 错误 : invalid instruction suffix for `cmpxchg'

c++ - 为什么 C++ POD 结构没有默认散列?

algorithm - 树编辑距离 : How can I get the optimal mapping?

ruby - 如何在 HAML 中构建嵌套菜单 "trees"

java - 如何正确使用共享BlockingQueue?

c++ - Eigen 库和 C++ 链接器的问题

c++ - 将 wavs 加载到内存中,然后使用 Win32 API 异步播放声音

c++ - std::function 可以有函数指针作为类型吗?

sql - 如何使 SQL 根据具有相同标签的项目创建标签层次结构?

python - Graphviz 决策树