Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 二叉树的擦除函数出错?(C+;+;)_C++_Crash_Binary Tree_Erase - Fatal编程技术网

C++ 二叉树的擦除函数出错?(C+;+;)

C++ 二叉树的擦除函数出错?(C+;+;),c++,crash,binary-tree,erase,C++,Crash,Binary Tree,Erase,所以我正在研究一个二叉树的擦除函数,其中一个键是给定的,根是作为参数给定的。 树的结构定义如下: struct BST_Node { string key; string things; //not relevant to this function BST_Node * left, * right; }; typedef BST_Node * BST; 然而,由于某种原因,我的第一个案例在我尝试运行时不断崩溃 void BST_delete(string key, BST

所以我正在研究一个二叉树的擦除函数,其中一个键是给定的,根是作为参数给定的。 树的结构定义如下:

struct BST_Node {
 string key;
 string things;   //not relevant to this function
 BST_Node * left, * right;
};
     typedef BST_Node * BST;
然而,由于某种原因,我的第一个案例在我尝试运行时不断崩溃

void BST_delete(string key, BST & tree) {

//before is just the predecessor 
BST_Node* before = NULL;
BST_Node* current = tree;

while(current!= NULL){
    if(current->key == key)
    {
        break;
    }
    else{
        before = current;   //the node before current
        if( key < current->key)
        {
            current = current->right;
        }
        else{
            current = current->left;
        }
        }
}


//FIRST CASE - has no children, so just deleting the Node.
          //then assigning the "before" node to point to NULL since it was originally       pointing to the node that was just deleted. 
 (need to check if the left or right of "before" pointed to "current"

if(current -> left == NULL && current->right==NULL)
{
    if(before->right == current)
    {
        before->right == NULL;
    }
    else if(before->left == current)
    {
        before->left == NULL;
    }

    delete current;
}
void BST\u delete(字符串键、BST和树){
//以前只是前辈
BST_Node*before=NULL;
BST_节点*当前=树;
while(当前!=NULL){
如果(当前->键==键)
{
打破
}
否则{
before=current;//当前之前的节点
如果(键<当前->键)
{
当前=当前->右侧;
}
否则{
当前=当前->左侧;
}
}
}
//第一种情况-没有子节点,因此只需删除节点。
//然后将“before”节点指定为NULL,因为它最初指向的是刚刚删除的节点。
(需要检查“before”的左侧或右侧是否指向“current”
如果(当前->左==NULL&当前->右==NULL)
{
如果(在->右==当前之前)
{
前->右==NULL;
}
否则如果(在->左==当前之前)
{
before->left==NULL;
}
删除当前文件;
}

您访问
current->left
,而不检查
current==NULL
:更改为:

if(current && current->left == NULL && current->right==NULL)
编辑:您可能希望将if(keykey)更改为

if( key > current->key)

一旦你完成了Chris Maes建议的测试,你也需要改变

before->right == NULL;
作业中只能有一个=。将其更改为

before->right = NULL;

你的函数BST_delete到底应该做什么?你得到了什么错误?@ChrisMaes你得到了一个需要删除的节点(目标节点),同时也给出了引用该节点的键。它只是在我运行它时崩溃。它确实编译。啊,你是对的。我放了一个断言(current!=NULL)我把标志换成了>,我不知道我是怎么把它弄混的。但是,我似乎仍然没有让它正常工作。逻辑是有道理的,对吗?