C 如何在二叉搜索树的右子树中找到最小值
我正在尝试在二叉搜索树中创建一个删除函数。 我已经完成了deletion函数,但是FindMin()函数有如下问题:C 如何在二叉搜索树的右子树中找到最小值,c,binary-search-tree,C,Binary Search Tree,我正在尝试在二叉搜索树中创建一个删除函数。 我已经完成了deletion函数,但是FindMin()函数有如下问题: BST* delete_node(BST* root, int key) { BST* temp; if (root == NULL) return root; else if (key < root->key) root->left_child = delete_node(root->left_child, key); else if (
BST* delete_node(BST* root, int key)
{
BST* temp;
if (root == NULL)
return root;
else if (key < root->key)
root->left_child = delete_node(root->left_child, key);
else if (key > root->key)
root->right_child = delete_node(root->right_child, key);
else //If the key is found delete it according to the following cases
{
if (root->left_child == NULL && root->right_child == NULL)
{
free(root);
root = NULL;
}
else if (root->left_child == NULL){ //right child exists
temp = root;
root = root->right_child;
free(temp);
}
else if (root->right_child == NULL){ //left child exists
temp = root;
root = root->left_child;
free(temp);
}
else{
temp = FindMin(root->right_child);
root->key = temp->key;
root->right_child = delete_node(root->right_child, temp->key);
}
}
return root; /*Returning the address of node to be reattached to
the parent of the deleted node*/
}
BST* FindMin(BST* root) //This functions finds the minimum key value in the
right subtree
{
BST* temp = NULL;
if (root->left_child != NULL)
{
temp = FindMin(root->left_child);
return temp;
}
else
return root;
}
BST*删除节点(BST*根,int键)
{
英国标准时间*温度;
if(root==NULL)
返回根;
否则如果(键<根->键)
根->左\子节点=删除\节点(根->左\子节点,键);
否则如果(键>根->键)
root->right\u child=删除节点(root->right\u child,key);
else//如果找到密钥,请根据以下情况删除它
{
if(root->left\u child==NULL&&root->right\u child==NULL)
{
自由根;
root=NULL;
}
如果(root->left_child==NULL){//存在右子项,则为else
温度=根;
根=根->右\u子项;
免费(临时);
}
如果(root->right\u child==NULL){//存在左子项,则为else
温度=根;
根=根->左\子项;
免费(临时);
}
否则{
temp=FindMin(根->右\u子项);
根->键=临时->键;
root->right\u child=删除节点(root->right\u child,temp->key);
}
}
return root;/*返回要重新连接到的节点的地址
已删除节点的父节点*/
}
BST*FindMin(BST*root)//此函数在
右子树
{
BST*temp=NULL;
if(root->left_child!=NULL)
{
temp=FindMin(根->左\u子项);
返回温度;
}
其他的
返回根;
}
我很确定我需要修复FindMin()函数才能使其正常工作。但是我的delete函数遇到了问题,因为每次我删除一个节点时,它都会给出一个错误,我认为这是因为FindMin()。这就是我如何进行二叉搜索树的 结构如下:
struct _Node;
typedef struct _Node* Position;
struct _Node
{
int element;
Position left;
Position right;
};
这是搜索最小值的功能:
Position SearchMin(Position P)
{
while(P->left != NULL)
{
P = P->left;
}
return P;
}
您是否测试过
FindMin()
?它在树中查找最小节点。如果您想要右子树中的最小节点,请调用FindMin(root->right\u child)
。。每当我执行程序时,代码中偶尔会出现运行时错误。我没有从代码中看到任何逻辑错误,但有些地方出了问题。是的,我在delete_节点函数中尝试了FindMin(root->right_child)。谢谢!它可以工作:)只是在处理最后一个空值时遇到了问题,而我在到达二叉搜索树中的最小值节点时总是遇到这个空值。