BST有序递归:查找大于K的第一个节点

问题描述

我的代码似乎一直运行到最后(因此返回None),而不是在找到子树时停止。

def first_greater_than_k(tree,k):
    if not tree: 
        return None

    first_greater_than_k(tree.left,k)

    if tree.data > k:
        return tree
        
    first_greater_than_k(tree.right,k)

解决方法

那是因为您没有在 first_greater_than_k 函数中返回任何值。另外,如果您拥有BST(二分搜索树),则可以比线性搜索做得更好。

问题:遍历树时查找大于K的第一个节点。

def first_greater_than_k(tree,k):
    if not tree: 
        return None
    if tree.data > k:
        return tree
    return first_greater_than_k(tree.right,k)

您不需要递归树的左孩子,因为那里存储的值总是比树的值低。运行时间为O(h),其中h是树的高度。

另外,一个更有用的问题是(也许这是您的要求,但我们没有得到):
如果进行有序遍历,则找到大于K的第一个节点。

我们可以使用Bem属性来解决该问题,该属性在第三版《算法入门》 (Cormen,第287页)中说明

x 成为二叉搜索树中的节点。如果 y 是左侧子树中的节点 ( x ),然后 y.key x.key 。如果 y x 右子树中的节点,则 y.key x.key

def first_greater_than_k(tree,k):
    if not tree: 
        return None
    if k < tree.data:
        x = first_greater_than_k(tree.left,k)
        return x if x else tree
    return first_greater_than_k(tree.right,k)

此代码的运行时间为O(h),其中h是树的高度。

,

无递归的原始答案:

def first_greater_than_k(tree,k):
    subtree,first_so_far = tree,None

    while subtree:
        if subtree.data > k:
            first_so_far,subtree = subtree,subtree.left
        else:
            subtree = subtree.right
    
    return first_so_far
,

通过代码,我可以猜测您要返回其子树 根的值大于K。

在这种情况下,您可以通过适当地减少一半来真正提高搜索运行时的复杂性。想法是将树分成两半,然后根据K的值选择正确的两半。

注意:我不知道您使用的语言,请忽略语法错误。

def first_greater_than_k(tree,k):
    if not tree: 
        return None

    if tree.data < k
        return first_greater_than_k(tree.left,k)
    
    if(tree.data > k)
        return tree;
        
    return first_greater_than_k(tree.right,k)

整个运行时复杂度为O(log N),其中N是树中的节点数。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...