I am trying to delete a node from a binary tree and am getting a nullptr error. If anyone would please give me some pointers on what to look for, I would greatly appreciate it.
void BinTree::deleteItem(int val)
{
MyNode *trailCurrent = nullptr;
MyNode *current = root; //pointer to traverse the tree
MyNode *temp;
bool found = false;
if (root == nullptr)
{
cout << "Cannot delete from the empty tree." << endl;
return;
}
//find the node to be deleted
while (current != nullptr && !found)
{
if (current->info == val) //if value is found
found = true;
else //while value is not found
{
trailCurrent = current;
if (val < current->info) //if value is less than current's info
current = current->llink; //traverse the left side of the tree
else
current = current->rlink; //otherwise traverse the right side of the tree
}
}
if (current = nullptr)
cout << "The item to be deleted is not in the tree." << endl;
elseif (found) //delete pointers to node
{
//node is a leaf
trailCurrent = current;
if (current->llink == NULL && current->rlink == NULL)
{
if (trailCurrent->llink == current)
trailCurrent->llink = NULL;
else
trailCurrent->rlink = NULL;
delete current;
}
//node has 2 children
elseif ((current->llink != NULL) && (current->rlink != NULL))
{
current = trailCurrent->llink;
// trailCurrent = NULL;
while (current->rlink != NULL)
{
trailCurrent = current;
current = current->rlink;
}
trailCurrent->info = current->info;
if (trailCurrent == NULL)
trailCurrent->llink = current->llink;
else
trailCurrent->rlink = current->llink;
delete current;
}
//node has 1 child
else
{
if (trailCurrent->llink == NULL)
{
temp = trailCurrent;
trailCurrent = temp->rlink;
delete temp;
}
else
temp = trailCurrent;
trailCurrent = temp->llink;
delete temp;
}
}
}