簡體   English   中英

從二叉搜索樹中刪除?

[英]Deleting from a Binary Search Tree?

我正在嘗試從二叉搜索樹中刪除,並在調試器中不斷收到此錯誤,並且不確定如何糾正它。 此代碼正確嗎?

程序收到信號EXC_BAD_ACCESS,無法訪問內存。 原因:在地址:0x0000000000000000 0x00007fff8cc17fe2在std :: string :: compare()中的KERN_INVALID_ADDRESS

void remove( const Comparable & x, BinaryNode *& t )
{
    if (t != NULL)
    {
        if(t->element.find(x) != std::string::npos)
        {
            if( t->left != NULL && t->right != NULL ) // Two children
            {
                t->element = findMin( t->right )->element;
                remove( t->element, t->right);
            }
            else
            {
                BinaryNode *oldNode = t;
                t = ( t->left != NULL ) ? t->left : t->right;
                delete oldNode;
                cout << "Successly deleted!" << endl;
            }
        }
        if(x < t->element)
        {
            remove(x, t->left);
        }
        else
        {
            remove(x, t->right);
        }
    }
    else 
    {
        cout << x << "<-could not delete?" << endl;            
    }     
}

首先,使用調試設置進行編譯,然后在調試器下運行它 我可以保證一切,但它會完全解決您失敗案例的位置。

關於這一點,我推測這是這一行:

if(x < t->element)  // <==== here
{
    remove(x, t->left);
}
else
{
    remove(x, t->right);
}

由於某種原因,在此之前您的邏輯需要進行以下推導:

  • 左邊或右邊都不為空
  • 僅左或右為空

你不解釋的情況下,當 ,右都為空,如將是一個樹的葉節點的情況。 因此,這取自您的else條件:

BinaryNode *oldNode = t;
t = ( t->left != NULL ) ? t->left : t->right;
delete oldNode;
cout << "Successly deleted!" << endl;

如果是葉節點,則將t設置為null,此代碼將在此答案的開頭立即將其取消引用。

您需要為此重新設計邏輯,並且如果取消引用之前的代碼可以使被取消引用的指針無效,則需要首先對其進行檢查。

最后,如果您想知道那是有問題的行的提示,則您得到報告字符串比較的特定錯誤是取消引用空ptr。 除了通過該operator <重載,字符串比較不會在此函數的其他任何地方進行。

暫無
暫無

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

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