我有一个函数可以计算小于二叉搜索树中项目的数字。它工作正常。但我只是不明白为什么局部变量计数可以记住总数,因为每次递归调用,它都会重置为 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