[英]Deleting node with two children in binary search tree
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: 删除22
会导致:
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. 当您DeleteNode(temp)
,旧节点仍在树中,但temp
被覆盖。 You meant to overwrite the parent's right
member. 您打算覆盖父母的right
成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.