【问题标题】:BST in-order recursion: Finding the first node that's greater than KBST中序递归:找到大于K的第一个节点
【发布时间】:2021-01-08 21:24:57
【问题描述】:

我的代码似乎一直运行到最后(因此返回 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)

【问题讨论】:

  • 这是什么编程语言?
  • 它是python...

标签: recursion binary-search-tree tree-traversal inorder


【解决方案1】:

那是因为您没有在 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 的第一个节点。

我们可以使用算法简介(Cormen,第 287 页),第 3 版一书中所述值的 BST 属性来解决它:

x 为二叉搜索树中的一个节点。如果 y 是左子树中的一个节点 x,则 y.keyx.key。如果 yx 的右子树中的一个节点,那么 y.keyx.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 是树的高度。

【讨论】:

  • 谢谢埃洛伊!我有第 2 版,我在 p257 上找到它 :)。你是对的,问题是按顺序遍历。我一直在寻找递归解决方案,只是为了更好地理解递归。无论如何,你的回答真的很有帮助。谢谢!
【解决方案2】:

没有递归的原始答案:

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

【讨论】:

    【解决方案3】:

    通过代码我可以猜到您想要返回其子树 root的值大于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 是树中的节点数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 2013-01-04
      相关资源
      最近更新 更多