Get the height of a BST

BinarySearchTree.prototype.height = function () {
  
  if (this.right === null && this.left === null) return 1;
  var heightLeft = 0;
  var heightRight = 0;
    if(this.left!=null)
   heightLeft = this.height(this.left);
    if(this.right!=null)
   heightRight =this.height(this.right);
    if(heightLeft > heightRight){
        return heightLeft+1;
    }
    else{
        return heightRight+1;
    }
}; 

I need to get the height of the BST and i see the theory but i want that the root counts as 1 and not as 0 .

So if i had a BST like this :

//             16             ---> lvl1

//          /      \

//        6         23        ---> lvl2

//      /  \       /   \

//     2    14    17    31    ---> lvl3

//      \

//       5                    ---> lvl4  
As its can be seen, the endheight its going to be 4 in the example.

Sorry for my band inglish

I can count every “node” of the three but idk how to do the height:

BinarySearchTree.prototype.size = function () {
  if (this.right === null && this.left === null) return 1;
  if (this.right === null && this.left !== null) return 1 + this.left.size();
  if (this.right !== null && this.left === null) return 1 + this.right.size();
  if (this.right && this.left) return 1 + (this.left.size() + this.right.size());
};

It looks like you are recursively trying to count nodes by counting the left and right child nodes of each node. If so, you just need to add a comparison to return the larger number from each child (or smaller if you want the min) and add the return values as the recursion unwinds instead of adding both sides like you are to count the nodes.

If you want to include the root node in the height and it’s not already, just add one.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.