简体   繁体   English

在Binary搜索树中打印K个最小值

[英]printing K lowest values in Binary search tree

I am trying to figure out how to print the lowest k values in a binary search tree. 我试图弄清楚如何在二进制搜索树中打印最低的k值。 I an having trouble stopping the method 我无法停止该方法

code: 码:

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)

Currently my output simply printed the whole tree inorder 目前我的输出只是按顺序打印了整棵树

Changes to the value of count don't propagate back up to the caller. count值的更改不会传播回调用者。 You need to return the new 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

Also note you don't need both k and count . 还要注意,您既不需要k也不需要count You can get rid of count , decrement k instead of incrementing count , and compare k against 0 (instead of against count ). 您可以摆脱count ,减少k而不是递增count ,然后将k与0(而不是对count )进行比较。 Here's what you get: 这是您得到的:

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

It's a rather "functional programming" solution, but one way is to generate (lazily) the nodes in the tree in order, and then using itertools to just take the first k. 这是一个相当“功能性的编程”解决方案,但是一种方法是依次生成(延迟)树中的节点,然后使用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)

If you're using Python 3, you can use "yield from" to make this solution shorter. 如果您使用的是Python 3,则可以使用“ yield from”来简化此解决方案。

You need to change things around a bit so you know how many elements were found during the recursive call. 您需要进行一些更改,以便您知道在递归调用中找到了多少个元素。 Have the function return the number of elements it found an add them up. 让函数返回它发现的元素的数量并加起来。 Also you need to check the count between the recursive calls and the current node's element. 另外,您还需要检查递归调用与当前节点元素之间的计数。

Something like: 就像是:

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
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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM