我有一個函數可以計算二進制搜索樹中小於項的數。它工作正常。但我只是不明白爲什麼局部變量的數量還記得總因爲每次遞歸調用,將被重置爲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