我想創建一個方法,告訴我一個二叉樹的高度,最簡單的方法是使用遞歸,但由於某種原因,我的一個變量即使重新設置,即使我以爲我在檢查所以它會保持不變...
這裏是我的代碼
遞歸和常量變量
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不會被重置,並且會在整個遞歸過程中隨時保持找到的最大值。
注意你的矛盾。常量不是可變的,變量不是(必然)是常量。你的問題是你正在通過一個值來傳遞一個變量,這會產生一個副本。更改副本不會更改從中複製的變量。 –