Generate two BSTs from the given array such that maximum height among them is minimum
Given an array of n integers where n is greater than 1, the task is to make two Binary Search Tree from the given array (in any order) such that the maximum height among the two trees is minimum possible and print the maximum height.
Examples:
Input: arr[] = {1, 2, 3, 4, 6}
Output: 1
Input: arr[] = { 74, 25, 23, 1, 65, 2, 8, 99 }
Output: 2
Approach: The aim is to minimize the height of the maximum height binary search tree and to do so we need to divide the array elements equally among both the trees. And since the order doesn’t matter, we can easily choose any element for the first or second binary tree. Now, to minimize the height of the two tree, the trees will have to be almost complete and as equal in heights as possible. And the maximum (minimized) height will be log(n/2) or log(n/2 + 1).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int cal_log( int n)
{
int ans = 0;
while (n) {
n /= 2;
ans++;
}
return ans;
}
int maximumHeight( int n, int arr[])
{
int level = cal_log(n / 2 + n % 2);
return (level - 1);
}
int main()
{
int arr[] = { 1, 2, 3, 4, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << maximumHeight(n, arr);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int cal_log( int n)
{
int ans = 0 ;
while (n > 0 )
{
n /= 2 ;
ans++;
}
return ans;
}
static int maximumHeight( int n, int arr[])
{
int level = cal_log(n / 2 + n % 2 );
return (level - 1 );
}
public static void main (String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 , 6 };
int n =arr.length;
System.out.print( maximumHeight(n, arr));
}
}
|
C#
using System;
class GFG
{
static int cal_log( int n)
{
int ans = 0;
while (n > 0)
{
n /= 2;
ans++;
}
return ans;
}
static int maximumHeight( int n, int []arr)
{
int level = cal_log(n / 2 + n % 2);
return (level - 1);
}
public static void Main ()
{
int []arr = { 1, 2, 3, 4, 6 };
int n =arr.Length;
Console.WriteLine( maximumHeight(n, arr));
}
}
|
Python3
def cal_log(n):
ans = 0 ;
while (n):
n / / = 2 ;
ans + = 1 ;
return ans;
def maximumHeight(n, arr):
level = cal_log(n / / 2 + n % 2 );
return (level - 1 );
arr = [ 1 , 2 , 3 , 4 , 6 ];
n = len (arr);
print (maximumHeight(n, arr));
|
Javascript
<script>
function cal_log(n)
{
var ans = 0;
while (n) {
n = parseInt(n/2);
ans++;
}
return ans;
}
function maximumHeight(n, arr)
{
var level = cal_log(parseInt(n / 2) + n % 2);
return (level - 1);
}
var arr = [ 1, 2, 3, 4, 6 ];
var n = arr.length;
document.write( maximumHeight(n, arr));
</script>
|
Time Complexity: O(log(N))
Auxiliary Space: O(1)
Last Updated :
04 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...