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

时间:2014-05-22 04:14:58

标签: c++ pointers binary-search-tree nodes delete-operator

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

以下是我的功能:

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  

1 个答案:

答案 0 :(得分:3)

temp = FindMax(r->left);

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