我有一个函数可以计算二进制搜索树中小于项的数。它工作正常。但我只是不明白为什么局部变量的数量还记得总因为每次递归调用,将被重置为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
谢谢,现在明白了。 – duckduck 2013-03-10 01:22:05