查找BST的最大值和最小值

时间:2015-05-12 18:57:05

标签: c binary-search-tree

你好stackoverflowers, 我在C中遇到了我的函数问题,我想创建一个函数,它给出了BST中的最小值和最大值。 问题是,当我使用此函数时,它返回min和max的相同值:

void Find_Min_Max(node *bt,int* maxint,int* minint)
{
    node *tmp = bt;
    if( bt == NULL)
    {
        *maxint = 0;  // Only if the tree contains nothing at all
        *minint = 0;  // Only if the tree contains nothing at all
    }
   if( bt->left)
       return Find_Min_Max(bt->left,&(*maxint),&(*minint));
   *minint = bt->data;
   if( tmp->right)
       return Find_Min_Max(tmp->right,&(*maxint),&(*minint));
   *maxint = tmp->data;
}

但是当我使用它给我一个最大/最小的结果时,我删除了这部分代码,一切都很完美:

if( tmp->right)
    return Find_Min_Max(tmp->right,&(*maxint),&(*minint));
*maxint = tmp->data;

知道这将如何运作? 提前谢谢。

3 个答案:

答案 0 :(得分:3)

在同一个函数中同时递归计算max和min并不容易/直观。我甚至会说这是不可能的,因为这是两次完全不同的遍历。

你应该有一个函数来获得最小值,一个函数来获得最大值,并在Find_Min_Max内调用每个函数。

这可能是一种方法:

int find_min(node *n) {
    if (n == NULL) {
        return 0;

    }
    while (n->left != NULL) {
        n = n->left;
    }
    return n->data;
}

find_max类似,但仅遍历右侧链接:

int find_max(node *n) {
    if (n == NULL) {
        return 0;
    }
    while (n->right != NULL) {
        n = n->right;
    }
    return n->data;
}

然后,find_min_max()很容易编码:

void find_min_max(node *bt, int *min, int *right) {
    *min = find_min(bt);
    *max = find_max(bt);
}

find_min()find_max()可以是递归的,但迭代方法具有使用常量内存的理想属性(从而避免了堆栈溢出)。

答案 1 :(得分:0)

要查找BST中的最小值,请从根目录开始跟随左子项链,直到到达没有左子项的节点。该节点包含最小值(即使它确实有一个正确的子节点)。

找到最大值的算法恰好是镜像:跟随正确的孩子链,直到到达没有正确孩子的节点。该节点包含最大值。

尝试同时执行两次遍历是没有意义的,因为它们遵循完全不同的路径。如果您希望单个函数同时发现最小值和最大值,那么该函数本身的递归就没有多大意义。但是,它可以将调用包装到两个单独的递归函数中,一个用于查找最小值,另一个用于查找最大值。

答案 2 :(得分:0)

在 BST 中查找最小值和最大值非常容易。请检查下面的两个代码片段,我解释了这些代码的工作原理。

public int minValueInBST(Node node){
    if (node == null) throw new IllegalStateException();
    Node current = node;
    while (current.leftChild != null) {
        current = node.leftChild;
    }
    return current.value;
}

要在 BST 中找到最小值,我们必须找到最左边的叶节点,因为该节点包含最小值。所以首先,我们检查根节点是否为空,如果为空则抛出 IllegalStateException 否则我们找到左节点,最后,我们返回左节点值。

public int maxValueInBST(Node node){
    if (node == null) throw new IllegalStateException();
    Node current = node;
    while (current.rightChild != null) {
        current = node.rightChild;
    }
    return current.value;
}

要在 BST 中找到最大值,我们必须找到最右边的叶节点,因为该节点包含最大值。所以首先,我们检查根节点是否为空,如果为空则抛出 IllegalStateException 否则我们找到正确的节点,最后,我们返回正确的节点值。

相关问题