什么是#34;读访问违规...是nullptr"?

时间:2016-12-10 22:15:28

标签: c++ binary-search-tree nullptr

我可以使用一些帮助。我一直试图让我的删除功能正常工作,但无论我做什么,它总是给我一个"是nullptr"错误。我的代码有点乱,因为我一直在恐慌并疯狂地尝试任何想到的东西。如果我需要,我准备重新开始。无论我在哪里寻找有关nullptr的信息都没有真正给出我实际理解的解释。我的理解是"是nullptr"当您尝试取消引用指针/节点时会出现错误,但我找不到一种方法来处理对我有意义的问题。任何帮助都非常感谢。我的代码是:

 `

BT::BT()
{
    node* root = NULL;
}

char BT::FindReplacement(node* parent, char param)
{
    if (parent == NULL) //In case someone tries to delete a node while there aren't any nodes in the Tree
    {
        return NULL;
    } 

    parent = parent->right;
    while (parent->left != NULL)
    {
        parent = parent->left;
    }

    return parent->data;
}

void BT::leafDriver()
{
    int count = 0;
    leafCount(root, count); 
}

void BT::leafCount(node* start, int count)
{


    if ((start->left == NULL) && (start->right == NULL))
    {
        count++;
    }

    if (start->left != NULL)
    {
        leafCount(start->left, count);
    }

    if(start->right != NULL)
    {
        leafCount(start->right, count);
    }
cout << " There are " << count << " number of leaves in the BST" << endl;

}


void BT::deletionDriver(char param)
{
    deletion(root, param);
}

void BT::deletion(node* parent, char param)
{

    if (parent->data < param) 
    {
        parent->left = parent->left->left;
        deletion(parent -> left, param);
        cout << "checking left node" << endl;
    }

    else if (parent->data > param)
    {
        parent->right = parent->right->right;
        deletion(parent->right, param);
        cout << "checking right node" << endl;
    }

    else if (parent->data == param)
    {
        //Case 1: No Children
        if (parent->left == NULL && parent->right == NULL)
        {
            delete parent;
            parent = NULL;

        }


        //Case 2: One Child
        else if ((parent->right == NULL) && (parent->left != NULL))
        {
            node* temp = parent;
            parent = parent->left;
            delete temp;
        }

        else if (parent->left == NULL)
        {
            node* temp = parent;
            parent - parent->right;
            delete temp;
        }

        //Case 3: Two Children
        else if ((parent->left != NULL) && (parent->right != NULL))
        {
            char tempParam;
            tempParam = FindReplacement(parent, param);
            parent->data = tempParam;
            deletion(parent->right, tempParam);
        }
    }

    else 
        cout << "Item is not found in BST" << endl;
}`

2 个答案:

答案 0 :(得分:0)

每当你有这样的代码:

parent = parent->right;

您需要检查新分配给父级的值是否为空。换句话说,您的代码应始终如下所示:

parent = parent->right;
if ( parent == nullptr ) {
    // handle null case
}
else {
    // handle case when there is another node
}

答案 1 :(得分:0)

while (parent->left != NULL)

将其更改为

while (parent != NULL)

它应该有效