2013-03-07 149 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成爲一個全局變量,並在每次調用時增加它,這是相當不太優雅的。

相關問題