c++ - 删除 AVL 树中的指针
问题描述
我一直在尝试制作平衡的二叉搜索树,目前正在制作删除功能。我试图删除元素的方式在旋转功能中起作用。
这是旋转功能:
void rightRotation(Object** currentNode)
{
auto child = (*currentNode)->leftChild;
auto c_bf = child->getBalanceFactor();
if (c_bf > 0) // RR rotation
{
auto originalNode = *currentNode;
originalNode->leftChild = child->rightChild;
child->rightChild = originalNode;
*currentNode = child;
}
else // RL rotation
{
// -L part of the rotation
auto originalChild = child;
child = child->rightChild;
(*currentNode)->leftChild = child;
originalChild->rightChild = child->leftChild;
child->leftChild = originalChild;
// R- part of the rotation
auto originalNode = *currentNode;
originalNode->leftChild = child->rightChild;
child->rightChild = originalNode;
*currentNode = child;
}
}
因此,该函数获取节点地址的地址,并将该节点的地址替换为新节点(子节点)的地址。
我试图围绕相同的逻辑构建一个删除功能,但它不起作用,我不明白为什么。
这是删除功能:
void del(Object** node)
{
if ((*node)->leftChild == NULL and (*node)->rightChild == NULL) // current node is a leaf
{
delete (*node);
(*node) = NULL;
//return;
}
else if ((*node)->rightChild == NULL)
{
auto newNode = (*node)->leftChild;
delete (*node);
(*node) = newNode;
//return;
}
else if((*node)->leftChild == NULL)
{
auto newNode = (*node)->rightChild;
delete (*node);
(*node) = newNode;
//return;
}
else // we have both childs
{
// find the smallest element bigger than the current node
// it will be the leftest element of the right child
auto replacementNode = (*node)->rightChild;
while (replacementNode->leftChild != NULL)
replacementNode = replacementNode->leftChild;
auto copy = new Object(*replacementNode);
copy->leftChild = (*node)->leftChild;
copy->rightChild = (*node)->rightChild;
delete (*node);
(*node) = copy;
del(&replacementNode);
}
balance();
}
我尝试调试,进入删除功能的地址与我从 &this->root->leftChild 获得的地址不同(我试图删除这个节点)
解决方案
推荐阅读
- docker - 在 Fedora 32 上使用 AWS SAM 命令在本地运行 lambda 函数时出现问题。Docker 问题
- angular - Angular 8微调器或加载器使用不相关的组件
- jmeter - HTTP URL 重写修饰符
- c# - 使用 Parallel.Invoke 运行两个任务并添加超时以防一个任务需要更长的时间
- javascript - 如何在我想基于它创建的自定义库中使用传单中提供的 distanceTo 方法?
- java - 无法滚动到appium android中回收器视图的底部
- python - Python Dash刷新页面不更新源数据
- azure - 在 Azure FunctionsStartup 的配置中运行一些启动任务
- python - TypeError: User() 得到了一个意外的关键字参数“confirm_password”
- algorithm - 哪个递归调用最有效?