-2
我试图在二叉搜索树中进行删除功能。 我已经完成与删除功能,但我有一些麻烦的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 (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;
}
我敢肯定,我将需要修复的FindMin()函数来完成这项工作。但是我在删除函数时遇到了问题,因为每次删除一个节点时,都会出现错误,我认为这是因为FindMin()。
你有*测试*'FindMin()'?它在树中找到最小节点。如果你想要在右侧子树中的最小节点,调用'FindMin(root-> right_child)'。 – Beta
虽然我已经尝试了几个小时.. 每当我执行程序时,偶尔会有代码出现运行时错误。 我没有看到代码中的任何逻辑错误,但有些错误。 是的,我已经在delete_node函数中尝试了FindMin(root-> right_child)。 – MasterGL