Hacker Rank - Day 22 : Binary Search Trees

                   Day 22 : Binary Search Trees

Solution In Java 8:


import java.util.*;

import java.io.*;

class Node{

    Node left,right;

    int data;

    Node(int data){

        this.data=data;

        left=right=null;

    }

}

class Solution{

public static int getHeight(Node root){
         return root == null ? -1 : 1 + Math.max(getHeight(root.left), getHeight(root.right));
    }
public static Node insert(Node root,int data){
        if(root==null){
            return new Node(data);
        }
        else{
            Node cur;
            if(data<=root.data){
                cur=insert(root.left,data);
                root.left=cur;
            }
            else{
                cur=insert(root.right,data);
                root.right=cur;
            }
            return root;
        }
    }
public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();
        Node root=null;
        while(T-->0){
            int data=sc.nextInt();
            root=insert(root,data);
        }
        int height=getHeight(root);
        System.out.println(height);
    }
}


Solution In Python 3: 

class Node:
    def __init__(self,data):
        self.right=self.left=None
        self.data = data
class Solution:
    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
    def getHeight(self,root):

        return -1 if root is None else 1 + max(self.getHeight(root.left), self.getHeight(root.right))
T=int(input())
myTree=Solution()
root=None
for i in range(T):
    data=int(input())
    root=myTree.insert(root,data)
height=myTree.getHeight(root)

print(height)       

Share:

0 comments:

Post a Comment