我想创建一个方法,告诉我一个二叉树的高度,最简单的方法是使用递归,但由于某种原因,我的一个变量即使重新设置,即使我以为我在检查所以它会保持不变...
这里是我的代码
递归和常量变量
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不会被重置,并且会在整个递归过程中随时保持找到的最大值。
注意你的矛盾。常量不是可变的,变量不是(必然)是常量。你的问题是你正在通过一个值来传递一个变量,这会产生一个副本。更改副本不会更改从中复制的变量。 –