如何结合findMin()和delete()来删除BST中的最小节点
How to combine findMin() and delete() to remove smallest node in a BST?
我有一个递归删除给定节点的recMove函数。我还有一个findMin函数,可以查找BST中的最小节点。我在合并两者时遇到问题,以便我可以删除最小(或最大(节点。这是我尝试做的,但它只是返回垃圾:完整代码:https://pastebin.com/HCVsUZ4S
//remove min node in BST
node * extractMin()
{
return recRemove(root, findMin(root));
}
//delete node from tree
node * recRemove(node * root, double data)
{
//3 cases: no children, one child, 2 children
if (root == NULL)
{
return NULL;
}
else if (data < root->data)
{
root->left = recRemove(root->left, data);
}
else if(data > root->data)
{
root->right = recRemove(root->right, data);
}
else
{
if (root->right == NULL && root->left == NULL) //no children
{
delete root;
root = NULL;
return root;
}
else if(root->left == NULL) //only right child
{
temp = root;
root = root->right;
delete temp;
return root;
}
else if(root->right == NULL) //only left child
{
temp = root;
root = root->left;
delete temp;
return root;
}
else //2 children
{
temp->data = findMin(root->right);
root->data = temp->data;
root->right = recRemove(root->right, temp->data);
}
}
return root;
}
//find min node in BST
double findMin(node * p)
{
if(p == NULL)
{
return -1;
}
else
{
//in a balanced BST the minimum node is the leftmost node so,
//we traverse the left subtree until we get to the leftmost node and return and remove it.
temp = p;
while(temp->left != NULL)
{
temp = temp->left;
}
return temp->data;
}
}
抱歉,还不能写评论(稍后会删除(
温度在哪里定义?如果它是一个全局变量,那么这可能是问题所在......
编辑:现在已经看到了帕塞宾.....temp 是一个成员变量。将其更改为局部变量。确保在离开函数之前将其删除。(最佳使用标准::unique_ptr<>(
相关文章:
- 比较C++中两个BST的节点
- 递归函数,用于计算 BST 中具有两个子节点的节点数
- 检查BST中每个节点的平衡因子并将其存储在节点中
- 删除BST节点:三重故障
- 如何在给定特定节点的BST中找到直接较大的元素
- 为什么我不能将从我的 BST 获取的这个节点推送到这个堆栈中?
- 在BST堆中删除节点免错误
- 如何结合findMin()和delete()来删除BST中的最小节点
- C bST删除节点会破坏排序算法
- 从BST删除节点时出错
- 在 BST 中插入节点时出现逻辑错误
- 递归地将 1 添加到 BST 中的所有节点,但具有最小数据的节点除外
- BST 节点删除 - 指针未正确删除
- 将节点插入 BST
- 删除BST中的节点
- 找到任何节点的BST高度
- 如何在BST中从最高到最低打印特定范围内的数字,访问的节点最少
- 从 BST 中删除唯一的节点
- 计算 BST 节点移除的时间复杂度
- 删除BST节点导致seg故障.处理步骤