所以我试图编写一个二叉搜索树,这个擦除函数给我一个seg错误。我的Node类有一个临时数据,指向左边和右边的指针。右子节点以及父节点。 我有一个函数find(临时密钥),它将节点*返回给保存密钥作为其数据的节点。所以在我的主要内容中,我有
Node<temp>* p = bTree->find(key);
查找功能有效,但是当我这样做时 bTree-&GT;擦除(P); 打印我的结果,iit编译,但我得到一个段错误。请帮忙,谢谢。
template <typename temp>
void BinTree<temp>::erase(Node<temp>* n){
if(!n->lChild && !n->rChild){ //n has no children
delete n;
n = nullptr;
}
else if(n->lChild && n->rChild){ //n has two children
Node<temp>* p = n->rChild;
while(p->lChild)
p = p->lChild; //p will be n's successor
n->data = p->data; //set the data to that of the successor
if(p->rChild){ //take care of p's right child if it has one
p->parent->lChild = p->rChild;
p->rChild->parent = p->parent;
}
delete p;
p = nullptr;
}
else{ //n only has one child
if(n->parent){
if(n->data < n->parent->data){ //n is a left child
if(n->lChild){ //n has only a left child
n->lChild->parent = n->parent;
n->parent->lChild = n->lChild;
}
else{ //n has only a right child
n->rChild->parent = n->parent;
n->parent->lChild = n->rChild;
}
}
else{ //n is a right child
if(n->lChild){ //n has only a left child
n->lChild->parent = n->parent;
n->parent->rChild = n->lChild;
}
else{ //n has only a right child
n->rChild->parent = n->parent;
n->parent->rChild = n->rChild;
}
}
}
else{ //n is the root and has no parent, but still only has one child
if(n->lChild)
root = n->lChild;
else
root = n->rChild;
}
delete n;
n = nullptr;
}
}
答案 0 :(得分:1)
你对指针有一些严重的误解。
重要的不仅是您要删除的节点本身,还有指向该节点的其他指针。
例如,看一下erase()中的第一个案例:
if(!n->lChild && !n->rChild){ //n has no children
delete n;
n = nullptr;
}
删除节点n。但是n的父亲仍然存储一个指向n ....的指针。