2017-04-23 123 views
-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()。

+1

你有*测试*'FindMin()'?它在树中找到最小节点。如果你想要在右侧子树中的最小节点,调用'FindMin(root-> right_child)'。 – Beta

+0

虽然我已经尝试了几个小时.. 每当我执行程序时,偶尔会有代码出现运行时错误。 我没有看到代码中的任何逻辑错误,但有些错误。 是的,我已经在delete_node函数中尝试了FindMin(root-> right_child)。 – MasterGL

回答

1

这就是我如何做二进制搜索树。

这是结构:

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; 
} 
+0

谢谢!它的工作原理:)刚刚处理最后的NULL时遇到问题,当我到达二进制搜索树中最小值的节点时,我总是遇到这些NULL。 – MasterGL