HackerRank Day 22


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, , 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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
class Node
    {
    public Node left,right;
    public int data;
    public Node(int data){
        this.data=data;
        left=right=null;
    }
    }
class Solution
    {
   
    static int getHeight(Node root)
    {
       
        if (root == null)
        {
            return -1;
        }


        int max_left=getHeight(root.left);
        int max_right=getHeight(root.right);


        if (max_left > max_right)
            return max_left +1;

        else
            return max_right+1;
      //Write your code here
    }
    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;
        }
    }
    static void Main(String[] args)
    {
        Node root = null;
        int T = Int32.Parse(Console.ReadLine());
        while (T-- > 0)
        {
            int data = Int32.Parse(Console.ReadLine());
            root = insert(root, data);
        }
        int height = getHeight(root);
        Console.WriteLine(height);

        Console.ReadLine();
    }
    }
 
    //class Program
    //{
    //    static void Main(string[] args)
    //    {
    //    }
    //}
}

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6