Reputation: 21
I could use some help. I have been trying to get my deletion function to work correctly, but no matter what I seem to do it always gives me a "was nullptr" error. My code is a bit messy since I've been panicking and frantically trying anything that comes to mind. I am ready to start over if I need to though. Everywhere I have looked for information about nullptr has not really given an explanation that I actually understand. My understanding is that a "was nullptr" error is given when you try to dereference a pointer/node, but I could never find a way to handle the issue that made sense to me. Any help is really appreciated. My code is:
`
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;
}`
Upvotes: 2
Views: 14657
Reputation: 21
while (parent->left != NULL)
changed it to
while (parent != NULL)
and it should work
Upvotes: 0
Reputation:
Whenever you have code like this:
parent = parent->right;
you need to check that the value you have newly assigned to parent is not null. In other words your code should always look something like this:
parent = parent->right;
if ( parent == nullptr ) {
// handle null case
}
else {
// handle case when there is another node
}
Upvotes: 1