Today we are going to solve HackerRank Day 22 : Binary Search Trees 30 days of code solution in C, C++, Java, Python & Javascript.
Objective
Today, we’re working with Binary Search Trees (BSTs).
Task
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.
Input Format
The locked stub code in your editor reads the following inputs and assembles them into a binary search tree:
The first line contains an integer, n, denoting the number of nodes in the tree.
Each of the n subsequent lines contains an integer, data, denoting the value of an element that must be added to the BST.
Output Format
The locked stub code in your editor will print the integer returned by your getHeight function denoting the height of the BST.
Sample Input
7
3
5
2
1
4
6
7
Sample Output
3
Explanation
There are 4 nodes in this path that are connected by 3 edges, meaning our BST’s height = 3. Thus, we print 3 as our answer.
HackerRank Day 22 : Binary Search Trees 30 days of code solution
Binary Search Trees HackerRank Solution in C
int getHeight(Node* root){ //Write your code here if (root==NULL) return 0; else if ((root->left==NULL) && (root->right==NULL)) return 0; else if ((root->left != NULL) && (root->right==NULL)) return 1+getHeight(root->left); else if ((root->left == NULL) && (root->right!=NULL)) return 1+getHeight(root->right); else{ int a, b; a=getHeight(root->left); b=getHeight(root->right); if(a>b) return 1 + a; else return 1 + b; } }
Binary Search Trees HackerRank Solution in C++
int getHeight(Node* root){ if (root==NULL) { return -1; } else { return 1 + std::max(getHeight(root->left),getHeight(root->right)); } }
Binary Search Trees HackerRank Solution in Java
public static int getHeight(Node root){ if (root == null) return -1; return Math.max(getHeight(root.left), getHeight(root.right)) + 1; }
Binary Search Trees HackerRank Solution in Python 3
def getHeight(self,root): if root is None: return -1 hL = self.getHeight(root.left) hR = self.getHeight(root.right) if hL > hR: return 1+hL else: return 1+hR
Binary Search Trees HackerRank Solution in JavaScript
// Add your code here
var height = 1;
var height_left = -1;
var height_right = -1;
if (root.left)
height_left = this.getHeight(root.left);
if (root.right)
height_right = this.getHeight(root.right);
height += (height_left > height_right ? height_left : height_right);
return height;
NEXT : HackerRank Day 23 : BST Level order traversal 30 days of code solution
30 Days of Code HackerRank Solutions List – Day 0 to Day 29