c++ - 试图从二叉搜索树中删除一个节点

标签 c++ null binary-search-tree

当我尝试在删除节点后显示我的树时出现内存错误。
这是我的移除(删除)方法:

void binarySearchTree::remove(int x, node * r)
{
    bool found = false;
    node * previous = NULL;

    if (root == NULL)
    {cout << "Tree is empty. Nothing to remove." << endl; return;}

    while (!found)
    {
        if (x < r->data)
        {
            previous = r;
            r = r->left;
        }
        else if (x > r->data)
        {
            previous = r;
            r = r->right;
        }
        else
            found = true;
    }


    if (r->left == NULL && r->right == NULL)        //case 1: node to be deleted is a leaf (no children)
    {
        delete r;
        return;
    }
    else if(r->left == NULL && r->right != NULL)    //case 2: node only has a right child
        previous->right = r->right;
    else if (r->left != NULL && r->right == NULL)   //case 2: node only has a left child
        previous->left = r->left;
    else
    {                                               //case 3: node has two children
        node * minNode = findMinNode(r->right);     //finds min node in the right sub tree
        r->data = minNode->data;
        delete minNode;
        return;
    }
    delete r;
}

我的 findMinNode 方法:

binarySearchTree::node * & binarySearchTree::findMinNode(node * r)
{
    if (r == NULL)      //if tree is empty
        return r;

    if (r->left == NULL && r->right == NULL)
        return r;
    else if (r->left != NULL)
        return findMinNode(r->left);
    else
        return findMinNode(r->right);
}

我的展示方式(使用前序遍历):

void binarySearchTree::display(node * r)
{
    if (r == NULL)
        return;

    display(r->left);
    cout << r->data << endl;
    display(r->right);
}

我正在使用公共(public) display() 方法,然后调用此私有(private) display(node * r) 方法。

我知道问题出在我使用 delete 时,因为当我单步执行代码并到达我的 display() 方法时,当它检查是否 r== NULL 在我刚刚删除的节点上,地址不是 NULL,地址为 0x000000000,而是 0x000000001。因此,我的程序会崩溃。我以前从未遇到过这个问题。任何帮助将不胜感激。

我应该补充一点,我按以下确切顺序插入了这些值:10、5、34、2、8、12、25、6、18、27、38、11。我试图删除值为 12 的节点因为它有两个 child 。

最佳答案

当您删除一个节点时,您需要将指向它的指针清零,在您的示例中,该指针可以是根节点、上一个->左节点或上一个->右节点。如果您将 previous 更改为 node ** 并让它指向 previous 指针(初始化为 &root),那么您可以只说 *previous = null *previous = r->right.

关于c++ - 试图从二叉搜索树中删除一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32708334/

相关文章:

c++ - 实现标记 union 的移动构造函数

c++ - 为什么来自常量 POD 对象的字段本身不是常量?

c - 无法打印二叉搜索树

data-structures - 二叉搜索树、2-3 树和 B 树的用法、优缺点

algorithm - 适用于事件日历应用程序的最佳数据结构

c++ - 使用#ifndef 时,.h 文件被多次添加

c++ - Taglib 从任意文件 c++ 中读取 ID3v2 标签

java - 一旦我退出函数(Java),对象的值为空

php - 仅当两个字段同时为空时,Mysql 才更新字段

iphone - 在 NSInteger 返回类型方法上返回 nil