I'm trying to delete a node with two children. However, my function is not completely removing the node from the tree, leaving a duplicate.
Here are my functions:
void Remove(Node *&r, int idx)
{
if(Search(r, idx))
{
if(idx < r->id) Remove(r->left, idx);
else if(idx > r->id) Remove(r->right, idx);
else DeleteNode(r);
//cout << "Account " << idx << " is now closed.";
}
else cout << "Account does not exist." << endl;
}
void DeleteNode(Node *&r)
{
Node *temp = r;
if(r->left == NULL && r->right != NULL)
{
r = temp->right;
delete temp;
temp = NULL;
}
else if(r->left != NULL && r->right == NULL)
{
r = temp->left;
delete temp;
temp = NULL;
}
else if(r->left == NULL && r->right == NULL)
{
r = NULL;
delete r;
}
else
{
// go to left of r and find largest value
temp = FindMax(r->left);
int tempID = temp->id;
float tempBal = temp->balance;
string tempString = temp->name;
DeleteNode(temp);
r->id = tempID;
r->balance = tempBal;
r->name = tempString;
}
}
Node* FindMax(Node *t)
{
while(t->right != NULL)
{
t = t->right;
}
return t;
}
Suppose I have this tree:
33
22 44
11 25
Deleting 22
leads to this:
33
22 44
22 25
temp = FindMax(r->left);
Not what you meant to do. When you DeleteNode(temp)
, the old node is still in the tree but temp
got overwritten. You meant to overwrite the parent's right
member.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.