繁体   English   中英

删除二叉搜索树中有两个孩子的节点

[英]Deleting node with two children in binary search tree

我正在尝试删除有两个孩子的节点。 但是,我的功能不是从树中完全删除该节点,而是留下一个副本。

这是我的功能:

void Remove(Node *&r, int idx)
{
    if(Search(r, idx))
    {
        if(idx < r->id)      Remove(r->left, idx);
        else if(idx > r->id) Remove(r->right, idx);
        else                 DeleteNode(r);

        //cout << "Account " << idx << " is now closed.";
    }
    else cout << "Account does not exist." << endl;
}

void DeleteNode(Node *&r)
{
    Node *temp = r;

    if(r->left == NULL && r->right != NULL) 
    {
        r = temp->right;
        delete temp;
        temp = NULL;
    }
    else if(r->left != NULL && r->right == NULL) 
    {
        r = temp->left; 
        delete temp;
        temp = NULL;
    }
    else if(r->left == NULL && r->right == NULL)
    {
        r = NULL;
        delete r;
    }
    else 
    {
        // go to left of r and find largest value
        temp = FindMax(r->left);

        int    tempID        = temp->id; 
        float  tempBal       = temp->balance;
        string tempString    = temp->name; 

        DeleteNode(temp);   

        r->id = tempID; 
        r->balance = tempBal;
        r->name = tempString;
    }
}

Node* FindMax(Node *t)
{
    while(t->right != NULL) 
    {
        t = t->right;
    }
    return t;
}

假设我有这棵树:

          33
    22          44 
11      25  

删除22会导致:

          33
    22          44 
22      25  
temp = FindMax(r->left);

不是你的本意。 当您DeleteNode(temp) ,旧节点仍在树中,但temp被覆盖。 您打算覆盖父母的right成员。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM