0

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.

1
  • Mind your oxymorons. Constants are not variable, and variables are not (necessarily) constant. Your problem is that you are passing a variable by value, which makes a copy. Changing the copy does not change the variable that it was copied from. Commented Oct 21, 2012 at 4:28

2 Answers 2

2

Things are simpler:

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

In your code you have a problem because maxheight is passed by value, not by reference.

Sign up to request clarification or add additional context in comments.

Comments

0

A function parameter has automatic storage duration (commonly called "on the stack"). This means each call to findHeight has its own variable named maxHeight. You increment one of these local variables right before its lifetime ends. And although you return the incremented value, you don't use that return value in the recursive calls.

Either use a reference parameter, or use the return values from the two recursive calls.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.