【发布时间】:2020-09-07 23:09:36
【问题描述】:
我正在用 C++ 实现一个二叉搜索树,但是代码有错误,当删除一个有 2 个子节点的节点时结果树连接不好,删除一个有 0 或 1 个子节点的方法效果很好.此代码基于此答案:https://stackoverflow.com/a/31698320/11053027。
编辑: 例如,如果按以下顺序添加值:17、12、25,然后我尝试删除作为根的 17,它被删除,所以当我尝试显示所有元素时:12、25,其中 25 为根。 但是如果现在我尝试删除12它并没有被删除,那么问题是在我第一次删除17时引起的。没有显示错误消息。
请你帮帮我。提前致谢。代码如下:
Node<E> *getSuccesor(Node<E> &node) const {
auto *Succesor = node.right;
while (Succesor != nullptr) {
if (Succesor->left == nullptr) return Succesor;
Succesor = Succesor->left;
}
return Succesor;
}
void remove(Node<E> &node) {
if (&node == nullptr) return;
int nChildren = numChildren(node);
Node<E> *child;
if (nChildren == 2) {
child = getSuccesor(node);
remove(*child);
child->parent = node.parent;
child->left = node.left;
child->right = node.right;
if (&node == root)
root = child;
else {
if (&node == node.parent->right)
node.parent->right = child;
else node.parent->left = child;
}
} else {
child = (node.left != nullptr ? node.left : node.right);
if (child != nullptr)
child->parent = node.parent;
if (&node == root)
root = child;
else {
if (&node == node.parent->left)
node.parent->left = child;
else node.parent->right = child;
}
}
Size--;
}
【问题讨论】:
-
确切的错误信息是什么?请在您的question 中详细说明。还将您的代码设为minimal reproducible example。
标签: c++ pointers data-structures reference binary-search-tree