如何找到给定级别中具有最小值的节点?

时间:2019-04-25 17:08:02

标签: recursion tree min

因此,我想编写一个递归函数,该函数在二叉搜索树中返回给定级别的最小值。 我已经编写了这段代码,但是仅当bst是完整的二进制搜索树时,它才有效。 (每个节点有2个子节点)。 范例: 如果我的树是:

根等于3

右子等于4

左子等于1

该调用是第1级的根,它返回1。这正是我想要的值。

但带有此树:(相同的调用) 根等于2

左孩子等于空

正确的孩子等于3

它返回0(NULL)。因为0 <3。当我希望它实际返回3时。

我使用的代码:

int minAtLevel(AVLNodePtr root, int level)
{
    // If the tree is empty
    if (root == NULL)
        return 0;

    // if level becomes 0, it means we are on
    // any node at the given level
    if (level == 0)
        return root->key;

    int x = minAtLevel(root->left, level - 1);
    int y = minAtLevel(root->right, level - 1);

    // return maximum of two
    return min(x, y);
}
Thanks.

0 个答案:

没有答案