【问题标题】:printing K lowest values in Binary search tree在二叉搜索树中打印 K 个最小值
【发布时间】:2014-05-30 20:05:18
【问题描述】:

我试图弄清楚如何在二叉搜索树中打印最低 k 值。我无法停止该方法

代码:

def kthSmallestBST(node,k, count):
    if node == None or count == k:
        return
    else:
        kthSmallestBST(node.left, k, count)
        count += 1
        print node.data
        kthSmallestBST(node.right, k, count)
        count += 1


kthSmallestBST(BST, 3, 0)

目前我的输出只是按顺序打印了整个树

【问题讨论】:

    标签: python binary-search-tree


    【解决方案1】:

    这是一个相当“函数式编程”的解决方案,但一种方法是按顺序(懒惰地)生成树中的节点,然后使用 itertools 只取第一个 k。

    def inorder(tree):
        if not tree: return
        for node in inorder(tree.left): yield node
        yield tree
        for node in inorder(tree.right): yield node
    
    def least(tree, k):
        return itertools.islice(inorder(tree), k)
    

    如果您使用的是 Python 3,则可以使用“yield from”来缩短此解决方案。

    【讨论】:

      【解决方案2】:

      count 值的更改不会传播回调用者。您需要返回新的计数:

      def kthSmallestBST(node,k, count):
          if node is None or count >= k:
              return 0
          else:
              count += kthSmallestBST(node.left, k, count)
              if count < k:
                  print node.data
                  count += 1
              count += kthSmallestBST(node.right, k, count)
              return count
      

      另请注意,您不需要同时使用 kcount。你可以去掉count,减少k而不是增加count,并将k与0(而不是count)进行比较。这是你得到的:

      def kthSmallestBST(node, k):
          if node is None or k <= 0:
              return 0
          k = kthSmallestBST(node.left, k)
          if k > 0:
              print node.data
              k -= 1
          k = kthSmallestBST(node.right, k)
          return k
      

      【讨论】:

      • 我正在尝试递减 k 方法,但我遇到了一些麻烦,这就是我所拥有的:def kthSmallestBST(node, k): if node == None or k = 0: print node.data k -= 1 kthSmallestBST(node.right, k)
      【解决方案3】:

      您需要稍微改变一下,以便知道在递归调用期间找到了多少元素。让函数返回它找到的元素数量并将它们相加。您还需要检查递归调用和当前节点元素之间的计数。

      类似:

      def kthSmallestBST(node, k, count):
          if node == None or count == k:
              return 0
          else:
              count += kthSmallestBST(node.left, k, count)
              if(count == k) 
                  return count
              print node.data
              count += 1
              count += kthSmallestBST(node.right, k, count)
              return count
      

      【讨论】:

      • @shx2 没做过多少python。真的没有 ++ 运算符吗?
      【解决方案4】:
      import unittest
      
      class BST(object):
      
          def __init__(self, key):
              self.key = key 
              self.left = None
              self.right = None
      
      
      def get_kth_smallest_keys(node, k): 
          """Return, as a list, `k` smallest keys in a binary search tree rooted at `node`.
      
          """
          smallest = []
          _get_kth_smallest_keys(node, k, smallest)
          return smallest
      
      def _get_kth_smallest_keys(node, k, smallest):
          """A helper function. Appends nodes to the given list, `smallest`, and stop
          when k reaches 0.
      
          Returns the number of nodes appended to said list.
      
          """
          if node is None or k == 0:
              return 0
          # first, recurse left, and we get the number of nodes appended to the list by that call
          nk = _get_kth_smallest_keys(node.left, k, smallest)
          # if that number already reduces our counter to zero, we fail fast, returning that same number
          if k - nk <= 0:
              return nk
          # otherwise, we can still append this node's key to the list
          smallest.append(node.key)
          # then we recurse right, with a counter that is less 1 (our append) and less nk (appended by the left recurse)
          nnk = _get_kth_smallest_keys(node.right, k - 1 - nk, smallest)
          # our return value is the sum of our append (1) and the appends from both recurse calls
          return nk + 1 + nnk 
      
      
      class BSTTest(unittest.TestCase):
      
          def test_smallest_keys(self):
              root = BST(10)
              root.left = BST(6)
              root.right = BST(15)
              root.left.right = BST(8)
              root.right.right = BST(20)
      
              self.assertEquals(get_kth_smallest_keys(root, 0), []) 
              self.assertEquals(get_kth_smallest_keys(root, 1), [6])
              self.assertEquals(get_kth_smallest_keys(root, 3), [6, 8, 10])
              self.assertEquals(get_kth_smallest_keys(root, 5), [6, 8, 10, 15, 20])
              self.assertEquals(get_kth_smallest_keys(root, 6), [6, 8, 10, 15, 20])
      
      
      if __name__ == '__main__':
          unittest.main()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-26
        相关资源
        最近更新 更多