In this HackerRank Day 22: Binary Search Trees problem solution The height of a binary search tree is the number of edges between the tree's root and its furthest leaf. You are given a pointer, root, pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of the binary search tree.

HackerRank Day 22: Binary Search Trees problem solution

Problem solution in Python programming.

    def getHeight(self,root):
        #Write your code here
        if root.right is not None:
            right = self.getHeight(root.right) + 1
        else:
            right = 0
        if root.left is not None:
            left = self.getHeight(root.left) + 1
        else:
            left = 0
        if right > left:
            return(right)
        else:
            return(left)
        
            
            



Problem solution in Java programming.

	public static int getHeight(Node root){
      //Write your code here
        if (root == null) {
            return - 1;
        }
      int leftHeight = getHeight(root.left) + 1;
      int rightHeight = getHeight(root.right) + 1;
      return Math.max(leftHeight, rightHeight);
    }




Problem solution in C++ programming.

		int getHeight(Node* root){
          //Write your code here
            if(root == NULL) {
        return -1;
    }
    else {
        int lDepth = getHeight(root->left);
       int rDepth = getHeight(root->right);
 
       /* use the larger one */
       if (lDepth > rDepth) 
           return(lDepth+1);
       else return(rDepth+1);
    }   
}
            
        




Problem solution in C programming.

int getHeight(Node* root){
    if (!root || (!root->left && !root->right))
        return 0;
    
    int left = 1 + getHeight(root->left);
    int right = 1 + getHeight(root->right);
    return left > right ? left : right;
}



Problem solution in Java programming.

        // Add your code here
        var heightLeft = 0;
        var heightRight = 0;

        if (root.left !== null) {
            heightLeft = this.getHeight(root.left) + 1;
        }

        if (root.right !== null) {
            
            heightRight = this.getHeight(root.right) + 1;
        }

        return (heightLeft > heightRight? heightLeft : heightRight);