二叉树的擦除功能出错? (C ++)

时间:2014-03-07 16:31:12

标签: 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 & 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;
}

2 个答案:

答案 0 :(得分:0)

您无需检查current -> left:是否更改为:

即可访问current == NULL
if(current && current->left == NULL && current->right==NULL)

编辑:可能您想将if( key < current->key)更改为

if( key > current->key)

答案 1 :(得分:0)

一旦你修复了Chris Maes建议的测试,你还需要更改

before->right == NULL;

在作业中应该只有一个=。将其更改为

before->right = NULL;