gpt4 book ai didi

c++ - 二叉搜索树查找和删除 [C++]

转载 作者:搜寻专家 更新时间:2023-10-31 02:13:09 25 4
gpt4 key购买 nike

目前,我正在尝试修复我正在使用递归执行的查找和删除功能。但是,我遇到的问题是什么时候到达案例二的结尾,如何确定它是导致案例零还是案例一。

以下是我尝试做的事情的简短描述:情况二(两个 child )- 与右子树的最小值交换,这导致情况零或情况一。

    bool findAndRemove(const Type& v)
{
return findAndRemove(root, nullptr, v);
}

bool findAndRemove(Node<Type> *fr, Node<Type> *parent, const Type& v) const
{
if (fr == nullptr)
{
return true;
}

if (v < fr->element)
{
return findAndRemove(fr->left, fr, v);
}
else if (v > fr->element)
{
return findAndRemove(fr->right, fr, v);
}
else
{
switch (GetChildren(fr))
{
case 0:
if (parent->left == fr)
{
parent->left = nullptr;
delete fr;
}
else
{
parent->right = nullptr;
delete fr;
}
break;
case 1:
if (parent->left == fr)
{
if (fr->left != nullptr)
{
parent->left = fr->left;
delete fr;
}
else
{
parent->left = fr->right;
}

}
else
{
if (fr->right != nullptr)
{
parent->right = fr->right;
delete fr;
}
else
{
parent->right = fr->left;
}
}
break;
case 2:
{
Node<Type> * swap = fr->right;
while (swap->left != nullptr)
{
swap = swap->left;
}

Type temp = fr->element; // 30
temp = swap->element; // 35
swap->element = fr->element; // 30
fr->element = temp;

//temp = swap->element;
//swap->element = temp;
//temp = fr->element;
break;
}
}
}
return false;
}

最佳答案

根据 the algorithm :

  • find a minimum value in the right subtree;
  • replace value of the node to be removed with found minimum. Now, right subtree contains a duplicate!
  • apply remove to the right subtree to remove a duplicate.

在您的代码中,swap 指向该右子树中的最小节点,因此如果您在该节点上调用您的 findAndRemove 函数,您可以简单地删除它。

{
// STEP 1: find a minimum value in the right subtree;
Node<Type> * swap = fr->right;
while (swap->left != nullptr)
{
swap = swap->left;
}

// STEP 2: replace value of the node to be removed with found minimum.
fr->element = swap->element;

// STEP 3: apply remove to the right subtree to remove a duplicate.
// Here you should call 'findAndRemove' on 'swap' node
break;
}

关于c++ - 二叉搜索树查找和删除 [C++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41735362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com