簡體   English   中英

嘗試從二叉搜索樹中刪除節點

[英]Trying to delete a node from a 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);
}

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

我知道問題出在我使用delete因為當我單步執行代碼並進入display()方法時,當它檢查我剛剛刪除的節點上是否r== NULL時,該地址不是NULL0x000000000但具有0x000000001 因此,我的程序將崩潰。 我以前從未遇到過這個問題。 任何幫助將不勝感激。

我應該補充一點,我按以下確切順序插入了這些值:10、5、34、2、8、12、25、6、18、27、38、11。我試圖刪除值為12的節點,因為它具有兩個孩子。

刪除節點時,您需要使指向該節點的指針為NULL,在您的示例中,該指針可以是root,previous-> left或previous-> right。 如果將上一個更改為node **並將其指向上一個指針(初始化為&root),則可以說*previous = null*previous = r->right

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM