2012-10-21 117 views
0

我想創建一個方法,告訴我一個二叉樹的高度,最簡單的方法是使用遞歸,但由於某種原因,我的一個變量即使重新設置,即使我以爲我在檢查所以它會保持不變...
這裏是我的代碼
遞歸和常量變量

template<class T> 
int findHeight(binaryTreeNode<T> , int leftHeight, int rightHeight, 
     int maxHeight) { 
    if (leftHeight >= rightHeight && leftHeight >= maxHeight) { 
     maxHeight = leftHeight; 
    } 
    else if (leftHeight < rightHeight && rightHeight >= maxHeight) { 
     maxHeight = rightHeight; 
    } 
    if (t != NULL) { 
     cout << "current leftHeight " << leftHeight << " current rightHeight " 
       << rightHeight << " current maxHeight " << maxHeight << endl; 

     findHeight(t->leftChild, ++leftHeight, rightHeight, maxHeight); 
     findHeight(t->rightChild, leftHeight, ++rightHeight, maxHeight); 
    } 
    return ++maxHeight; 
} 

這是當我嘗試這樣做我已經得到的輸出:

current leftHeight 0 current rightHeight 0 current maxHeight 0 
current leftHeight 1 current rightHeight 0 current maxHeight 1 
current leftHeight 2 current rightHeight 0 current maxHeight 2 
current leftHeight 2 current rightHeight 1 current maxHeight 2 
current leftHeight 1 current rightHeight 1 current maxHeight 1 
current leftHeight 2 current rightHeight 1 current maxHeight 2 
current leftHeight 3 current rightHeight 1 current maxHeight 3 
Returned value = 1 

任何人都可以幫我嗎?我該如何做到這一點,以便maxHeight不會被重置,並且會在整個遞歸過程中隨時保持找到的最大值。

+0

注意你的矛盾。常量不是可變的,變量不是(必然)是常量。你的問題是你正在通過一個值來傳遞一個變量,這會產生一個副本。更改副本不會更改從中複製的變量。 –

回答

2

事情是簡單的:

int findHeight(binaryTreeNode<T> *t){ 
    return t ? 1 + MAX(findHeight(t->leftChild), findHeight(t->rightChild)) : 0; 
} 

在你的代碼,因爲maxheight是按值傳遞,而不是參考有問題。

0

函數參數具有自動存儲持續時間(通常稱爲「在堆棧上」)。這意味着每個致電findHeight的電話都有自己的變量,名稱爲maxHeight。您在其生命週期結束之前增加其中一個局部變量。儘管您返回遞增值,但您不會在遞歸調用中使用該返回值。

可以使用引用參數,也可以使用兩次遞歸調用的返回值。