2013-03-07 153 views
1

我有一个函数可以计算二进制搜索树中小于项的数。它工作正常。但我只是不明白为什么局部变量的数量还记得总因为每次递归调用,将被重置为0。递归调用中的局部变量

def count_less(self, item): 
    """(BST, object) -> int 
    Return the number of items in BST that less than item. 
    """ 
    return BST.count_less_helper(self.root, item) 

# Recursive helper function for count_less. 
def count_less_helper(root, item): 
    count = 0 
    if root: 
     if root.item < item: 
      count += 1 
      count += BST.count_less_helper(root.left, item) 
      count += BST.count_less_helper(root.right, item) 
     elif root.item > item: 
      count += BST.count_less_helper(root.left, item) 
    return count 

回答

0

在函数开始时,您将count设置为0,但在将其返回给调用方之前,您将在后面的递归调用中添加所有计数。每个后来的函数都从0开始,但随后将1加上稍后调用的计数。

+0

谢谢,现在明白了。 – duckduck 2013-03-10 01:22:05

0

为什么局部变量count记得总

在事实上,它不会“记住”。

在递归的每个级别,count的值是从头开始使用递归调用返回的值派生的。

0

您需要将count传递给您进行的递归调用,以便它可以跟踪并递增它。或者,您可以让count成为一个全局变量,并在每次调用时增加它,这是相当不太优雅的。

相关问题