# Day 22: Binary Search Trees In Java | 30 Days Of Code | Hackerrank Programming Solutions

Hello Programmers/Coders, Today we are going to share solutions of Programming problems of 30 Days Of Code, HackerRank. At Each Problem with Successful submission with all Test Cases Passed, you will get an score or marks. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for Day 22: Binary Search Trees in Java-HackerRank Problem. We are providing the correct and tested solutions of coding problems present on HackerRank. If you are not able to solve any problem, then you can take help from our Blog/website.

Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.

Link for the ProblemDay 22: Binary Search Trees – Hacker Rank Solution

Day 22: Binary Search Trees – Hacker Rank Solution

### Problem:

Objective
Today, we’re working with Binary Search Trees (BSTs). Check out the Tutorial tab for learning materials and an instructional video!

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, , 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, , denoting the number of nodes in the tree.
Each of the  subsequent lines contains an integer, , 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

The input forms the following BST:

The longest root-to-leaf path is shown below:

There are  nodes in this path that are connected by  edges, meaning our BST’s . Thus, we print  as our answer.

Day 22: Binary Search Trees – Hacker Rank Solution
import java.util.Scanner;

/**
* @author Techno-RJ
*
*/
public class Day22BinarySearchTrees {
static class Node {
Node left, right;
int data;
Node(int data) {
this.data = data;
left = right = null;
}
}

public static int getHeight(Node root) {
return (root == null) ? -1 : Math.max(getHeight(root.left) + 1, getHeight(root.right) + 1);
}

public static Node insert(Node root, int data) {
if (root == null) {
return new Node(data);
} else {
Node cur;
if (data  0) {
int data = sc.nextInt();
root = insert(root, data);
}
sc.close();
int height = getHeight(root);
System.out.println(height);
}
}

Scroll to Top