简体   繁体   English

二进制搜索树删除节点

[英]Binary Search Tree Remove Node

I adapted my code from from this book: Data Structures and Algorithms by Mark Allen Weiss, 3rd edition. 我改编自本书的代码:Mark Allen Weiss第三版的“数据结构和算法”。

Every time I run it, it crashes. 每当我运行它时,它就会崩溃。 By request I'll add the entire Binary Tree code (its long). 根据要求,我将添加整个Binary Tree代码(其长)。 Whenever I try to run it in debug mode, I end up cycling between the first three if else statements in the remove() function, and then I end up getting this output: 每当我尝试在调试模式下运行它时,我都会在remove()函数中的前三个if else语句之间循环,然后最终得到以下输出:

"Unhandled exception at 0x0007300d in Project 4Draft.exe: 0xC0000005: Access violation reading location 0x003c0000." “在Project 4Draft.exe中0x0007300d处未处理的异常:0xC0000005:访问冲突读取位置0x003c0000。

I'm pretty sure this is a segfault, just trying to find the source. 我很确定这是一个段错误,只是尝试查找源。 Also, when I run it, it doesn't step into findMin() , but I included it because its within remove, and It's not fully tested yet. 另外,当我运行它时,它不会进入findMin() ,但是我将其包括在内,因为它已被移除,并且尚未经过全面测试。 Can anyone help me derive the source? 谁能帮我推算出来源吗?

Here is the remove function: 这是删除功能:

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;
    }

}

here is findMin(): 这是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);
    };

And here is what I call in my test file: 这就是我在测试文件中所说的:

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

Are you sure that your loop condition is correct? 您确定循环条件正确吗?

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

Maybe you should write something like: 也许您应该编写类似以下内容的内容:

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

or 要么

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