我正在尝试创建一种方法来告诉我二叉树的高度,最简单的方法是使用递归,但是由于某种原因,我的一个变量正在重置,即使我认为我正在检查,所以它会保持不变...
这是我的代码
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 不会被重置,并且会在整个递归过程中随时保持找到的最大值。