[英]How to remove Specific Node is Binary Search Tree?
我正在尝试删除特定的节点,但看不到问题出在哪里。
实际上,我是通过Find()
获取Node的,然后使用Remove()
删除它。
每当Delete()
触发时,程序就会崩溃。
bool RemoveNode(int key)
{
if (IsEmpty())
return false;
Node* r = Find(key,root);
if (r==nullptr)
return false;
return Remove(r);
}
bool Remove (Node* &r)
{
if (r->left==nullptr && r->right ==nullptr)
{
delete r;
r=nullptr;
return true;
}
if (r->left==nullptr)
{
Node* temp = r->right;
delete r;
r=nullptr;
r=temp;
return true;
}
if (r->right==nullptr)
{
Node* temp = r->left;
delete r;
r=nullptr;
r=temp;
return true;
}
Node* Max = FindMax(r->left);
r->data = Max->data;
Remove(Max);
return true;
}
Node* FindMax(Node* r)
{
if(r->right==nullptr)
return r;
return FindMax(r->right);
}
Node* Find(int key, Node* &r)
{
if (r==nullptr)
return nullptr;
if (r->data==key)
return r;
if (key < r->data)
return Find(key,r->left);
else
return Find(key,r->right);
}
显然,您的Remove()
函数旨在修改指向节点的指针,而与节点的位置无关:您无需传递原始指针,而是传递对指针的引用。 这样,您可以更新树的root
指针,将其left
或right
作为下一个的组成部分。 只要您在正确的引用中通过它,我认为代码就应该起作用。
变量r
实际上是在Remove()
修改的,它是RemoveNode()
定义的局部变量: Find()
的结果是一个指针,而不是对相关指针的引用。 但是,您需要修改树形结构中指向节点的指针,而不是任意的局部变量。
解决方法是使用Find()' which correctly returns a reference to the pointer rather than the pointer itself. Your recursive
的特殊版本,该版本Find()' which correctly returns a reference to the pointer rather than the pointer itself. Your recursive
Find()' which correctly returns a reference to the pointer rather than the pointer itself. Your recursive
Find() would be up to the task if it returned a
Node *& rather than a
Node *`, would be up to the task if it returned a
。 由于您的树似乎并不平衡并且堆栈空间相对有限,因此我宁愿使用非递归函数。 与其返回对指针的引用,不如保留指向当前节点的指针而不是指向该节点的指针:
Node** InternFind(int key) {
Node** n = &this->root;
while (*n && (*n)->key != key) {
n = &(key < (*n)->key? (*n)->left: (*n)->right);
}
return n;
}
该代码未经测试,可能不太正确。 但是,一旦获得指向该暂存器的指针,就可以对其进行更新,而无需处理其来源:
Node** r = InternFind(key);
if (*r) {
Remove(*r);
return true;
}
else {
return false;
}
虽然我不知道“如果Delete()
会触发”的含义,但我假设您对相同的指针p
重复使用delete p
存在问题。 该代码可能在访问失效节点之前就出错了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.