I am trying to create a method that will tell me the height a binary tree, the easiest way would be to use a recursion, however for some reason one of my variables is getting reset even though I thought I was checking so it would stay constant...
Here is my code
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;
}
This is the output I had gotten when I tried this:
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
Can anyone please help me? How can I make it so the maxHeight does not get reset and will hold the largest value found, anytime throughout the recursion.