【问题标题】:Binary Search Tree Remove Node二叉搜索树删除节点
【发布时间】:2013-11-01 20:31:56
【问题描述】:

我从这本书改编了我的代码:Mark Allen Weiss 的 Data Structures and Algorithms,第 3 版。

每次我运行它时,它都会崩溃。根据要求,我将添加整个二叉树代码(很长)。每当我尝试在调试模式下运行它时,我最终都会在 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";

【问题讨论】:

    标签: c++ binary-search-tree


    【解决方案1】:

    你确定你的循环条件是正确的吗?

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

    【讨论】:

    • 完全正确;描述使它看起来像一个无限循环或堆栈粉碎,这表明它是。
    • 我现在明白了,我把所有的时间都花在了查看类函数上。谢谢大家!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多