What is wrong with my CountHeight function for binary trees (Javascript)

var CountHeight = function(root){
    if(root == null){
       console.log("NULL!")
       return 0;
    }

    leftheight = CountHeight(root.left);
    rightheight = CountHeight(root.right);
    if (leftheight > rightheight){
        return leftheight + 1;
    } else if(rightheight > leftheight){
        return rightheight + 1;
    } else if(rightheight == leftheight){
        return leftheight + 1;
    }

}

Each root has a left and right value that points to another tree.

I tried to test out this function by plugging in a tree (I know the function takes a parameter called root but I’m basically passing a tree into it). The tree I passed on looked something like this:

(root)10: (leftofroot)left: 4 - left: null right: 8
(rightofroot)right: 15 - left: null right: null

If you cant follow the above diagram, I’m basically adding the following nodes ot my tree: 10, 4, 15, 8

Ok, so when I passed my tree into the function, I got the value of 2, but clearly my tree has a height of 3. The node 8 being the only node with that has a depth of 3.

So can someone tell me what’s going wrong with my function?

PS: I’m struggling, if my question is too confusing, can someone give me another function that finds the height of a tree when I pass a tree into it.

Thanks!

var testBST = new BST();
testBST.addNode(10);
testBST.addNode(4);
testBST.addNode(15);
testBST.addNode(8);

console.log(testBST);
console.log(CountHeight(testBST));

One thought on “What is wrong with my CountHeight function for binary trees (Javascript)”

  1. You could shrink the later conditions by using Math.max for getting maximum depth of left and right side.
    function countHeight(root) {
    return root
    ? 1 + Math.max(countHeight(root.left), countHeight(root.right))
    : 0;
    }

Leave a Reply

Your email address will not be published.