如何结合findMin()和delete()来删除BST中的最小节点

How to combine findMin() and delete() to remove smallest node in a BST?

本文关键字:BST 节点 删除 delete 何结合 结合 findMin      更新时间:2023-10-16

我有一个递归删除给定节点的recMove函数。我还有一个findMin函数,可以查找BST中的最小节点。我在合并两者时遇到问题,以便我可以删除最小(或最大(节点。这是我尝试做的,但它只是返回垃圾:完整代码:https://pastebin.com/HCVsUZ4S

//remove min node in BST
node * extractMin() 
{
    return recRemove(root, findMin(root));
}
//delete node from tree
node * recRemove(node * root, double data)
{
    //3 cases: no children, one child, 2 children
    if (root == NULL)
    {
        return NULL;
    }
    else if (data < root->data)
    {
        root->left = recRemove(root->left, data);
    }
    else if(data > root->data)
    {
        root->right = recRemove(root->right, data);
    }
    else
    {
        if (root->right == NULL && root->left == NULL) //no children
        {
            delete root;
            root = NULL;
            return root;
        }
        else if(root->left == NULL) //only right child
        {
            temp = root;
            root = root->right;
            delete temp;
            return root;
        }
        else if(root->right == NULL) //only left child
        {
            temp = root;
            root = root->left;
            delete temp;
            return root;
        }
        else //2 children
        {
            temp->data = findMin(root->right);
            root->data = temp->data;
            root->right = recRemove(root->right, temp->data);
        }
    }
    return root;
}
//find min node in BST
double findMin(node * p)
{
    if(p == NULL)
    {
        return -1;
    }
    else
    {
        //in a balanced BST the minimum node is the leftmost node so,
        //we traverse the left subtree until we get to the leftmost node and return and remove it.
        temp = p;
        while(temp->left != NULL)
        {
            temp = temp->left;
        }
        return temp->data;
    }
}

抱歉,还不能写评论(稍后会删除(

温度在哪里定义?如果它是一个全局变量,那么这可能是问题所在......

编辑:现在已经看到了帕塞宾.....temp 是一个成员变量。将其更改为局部变量。确保在离开函数之前将其删除。(最佳使用标准::unique_ptr<>(