HackerRank Day 22 Solution in Python: Binary Search Trees

Today we will see the HackerRank Day 22 Solution in Python. The problem is named Binary Search Trees which is part of 30 Days of code on HackerRank. Let’s get started!

Day 22: Binary Search Trees Problem statement

We are given a pointer, pointing to the root of a binary search tree. We have to complete the getHeight function provided so that it returns the height of the binary search tree. The height of a binary search tree is the number of edges between the tree’s root and its furthest leaf.

Sample Input

7
3
5
2
1
4
6
7

Sample Output

3

Explanation: The height of the given binary tree is 3

You can solve the problem here.

HackerRank Day 22 Solution in Python

class Node:
    def __init__(self,data):
        self.right=self.left=None
        self.data = data
        
class Solution:
    #Method to insert new data
    def insert(self,root,data):
        if root==None:
            return Node(data)
        else:
            if data<=root.data:
                cur=self.insert(root.left,data)
                root.left=cur
            else:
                cur=self.insert(root.right,data)
                root.right=cur
        return root
    
    #Function to get height of the tree
    def getHeight(self,root):
        #If root is null then return -1
        if root is None:
            return -1
        #recursive function call to calculate the height
        left = self.getHeight(root.left)
        right = self.getHeight(root.right)
        return max(left, right) + 1
        
T=int(input())
myTree=Solution()
root=None

#get input from the user for the tree
for i in range(T):
    data=int(input())
    root=myTree.insert(root,data)

#Call the getHeight method
height=myTree.getHeight(root)
#Print the height of the tree
print(height)

Code Explanation

  • We have created getHeight method inside the Solution class
  • In the getHeight method, if the root is null, then return -1
  • Else use a recursive function call to traverse through the tree
  • After reaching the end return the maximum value(left or right)

Also Read:

Share:

Author: Ayush Purawr