簡體   English   中英

二進制搜索樹刪除節點

[英]Binary Search Tree Remove Node

我改編自本書的代碼:Mark Allen Weiss第三版的“數據結構和算法”。

每當我運行它時,它就會崩潰。 根據要求,我將添加整個Binary Tree代碼(其長)。 每當我嘗試在調試模式下運行它時,我都會在remove()函數中的前三個if else語句之間循環,然后最終得到以下輸出:

“在Project 4Draft.exe中0x0007300d處未處理的異常:0xC0000005:訪問沖突讀取位置0x003c0000。

我很確定這是一個段錯誤,只是嘗試查找源。 另外,當我運行它時,它不會進入findMin() ,但是我將其包括在內,因為它已被移除,並且尚未經過全面測試。 誰能幫我推算出來源嗎?

這是刪除功能:

void remove(const T& x, TreeNode * & tn) const {
    if(tn == NULL)
        return;
    else if(x < tn->data)
        remove(x, tn->left);
    else if(tn->data < x)
        remove(x, tn->right);
    else if(tn->left != NULL && tn->right != NULL) {//Two Children(Swap the min of the right subtree, and swap
        tn->data = findMin(tn->right)->data;
        remove(tn->data,tn->right);
    }
    else{
        TreeNode *oldNode = tn;
        tn = (tn->left != NULL ) ? tn->left : tn->right;
        delete oldNode;
    }

}

這是findMin():

TreeNode * findMin(TreeNode *x) const {
        if(debugMode==true){
        cout << "\nWERE IN FINDMIN\n";
        }
        if(x==NULL){
            return NULL;
        }
        if(x->left==NULL){
            if(debugMode==true){
            cout << x;
            }
            return x;
        }

        return findMin(x->left);
    };

這就是我在測試文件中所說的:

cout << "Checking remove()\n";
    for(int i =SIZE; i>0;i++){
        z.remove(x[i]);
    }
    cout << "DONE Checking remove()\n";

您確定循環條件正確嗎?

for(int i =SIZE; i>0;i++){
    z.remove(x[i]);
}
cout << "DONE Checking remove()\n";

也許您應該編寫類似以下內容的內容:

for(int i = 0; i < SIZE; i++){
    z.remove(x[i]);
}

要么

for(int i = SIZE - 1; i >= 0; i--){
    z.remove(x[i]);
}

暫無
暫無

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

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