-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