簡體   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