Сгенерируйте два BST из данного массива, чтобы максимальная высота среди них была минимальной.
Учитывая массив из n целых чисел, задача состоит в том, чтобы создать два дерева двоичного поиска из данного массива (в любом порядке) так, чтобы максимальная высота между двумя деревьями была минимально возможной, и вывести максимальную высоту.
Примеры:
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++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to calculate the log() int cal_log( int n) { int ans = 0; while (n) { n /= 2; ans++; } return ans; } // Function to return the maximum // height of the tree int maximumHeight( int n, int arr[]) { int level = cal_log(n / 2 + n % 2); return (level - 1); } // Driven code int main() { int arr[] = { 1, 2, 3, 4, 6 }; int n = sizeof (arr) / sizeof (arr[0]); cout << maximumHeight(n, arr); return 0; } |
Java
// Java implementation of the approach import java.io.*; class GFG { // Function to calculate the log() static int cal_log( int n) { int ans = 0 ; while (n > 0 ) { n /= 2 ; ans++; } return ans; } // Function to return the maximum // height of the tree static int maximumHeight( int n, int arr[]) { int level = cal_log(n / 2 + n % 2 ); return (level - 1 ); } // Driver code public static void main (String[] args) { int arr[] = { 1 , 2 , 3 , 4 , 6 }; int n =arr.length; System.out.print( maximumHeight(n, arr)); } } // This code is contributed by anuj_67.. |
C#
// C# implementation of the approach using System; class GFG { // Function to calculate the log() static int cal_log( int n) { int ans = 0; while (n > 0) { n /= 2; ans++; } return ans; } // Function to return the maximum // height of the tree static int maximumHeight( int n, int []arr) { int level = cal_log(n / 2 + n % 2); return (level - 1); } // Driver code public static void Main () { int []arr = { 1, 2, 3, 4, 6 }; int n =arr.Length; Console.WriteLine( maximumHeight(n, arr)); } } // This code is contributed by anuj_67.. |
Python3
# Python implementation of the approach # Function to calculate the log() def cal_log(n): ans = 0 ; while (n): n / / = 2 ; ans + = 1 ; return ans; # Function to return the maximum # height of the tree def maximumHeight(n, arr): level = cal_log(n / / 2 + n % 2 ); return (level - 1 ); # Driver code arr = [ 1 , 2 , 3 , 4 , 6 ]; n = len (arr); print (maximumHeight(n, arr)); # This code is contributed by Princi Singh |
Javascript
<script> // Javascript implementation of the approach // Function to calculate the log() function cal_log(n) { var ans = 0; while (n) { n = parseInt(n/2); ans++; } return ans; } // Function to return the maximum // height of the tree function maximumHeight(n, arr) { var level = cal_log(parseInt(n / 2) + n % 2); return (level - 1); } // Driven code var arr = [ 1, 2, 3, 4, 6 ]; var n = arr.length; document.write( maximumHeight(n, arr)); </script> |
1
Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .
Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.