Finding height in Binary Search Tree

Posted by mike on Stack Overflow See other posts from Stack Overflow or by mike
Published on 2010-04-08T04:47:36Z Indexed on 2010/04/08 4:53 UTC
Read the original article Hit count: 297

Filed under:
|

Hey I was wondering if anybody could help me rework this method to find the height of a binary search tree. So far my code looks like this however the answer im getting is larger than the actual height by 1, but when I remove the +1 from my return statements its less than the actual height by 1? I'm still trying to wrap my head around recursion with these BST any help would be much appreciated.

public int findHeight(){
    if(this.isEmpty()){
        return 0;
    }
    else{
        TreeNode<T> node = root;
        return findHeight(node);
    }
}
private int findHeight(TreeNode<T> aNode){
    int heightLeft = 0;
    int heightRight = 0;
    if(aNode.left!=null)
        heightLeft = findHeight(aNode.left);
    if(aNode.right!=null)
        heightRight = findHeight(aNode.right);
    if(heightLeft > heightRight){
        return heightLeft+1;
    }
    else{
        return heightRight+1;
    }
}

© Stack Overflow or respective owner

Related posts about binary-trees

Related posts about homework