Check given array of size n can represent BST of n levels or not in C++


We have an array A, we have to check whether the array can represent a BST with n levels or not. As the level is , we can construct a tree in following manner. Assume a number is k, value greater than k moves to right side, and less than k moves to left side. Suppose two lists are there: {50, 20, 9, 25, 10}, and {50, 30, 20, 25, 10}

The first one is not valid, but the second one is valid.

To check this we can either create a BST and check the height, otherwise use array based approach. The array based approach is like below −

  • Take two variable max = infinity, to mark max limit of left subtree, and min = negative infinity to mark the minimum limit for the right subtree
  • for each element in range arr[i] to arr[n – 1], repeat following steps
    • if arr[i] > arr[i - 1] and arr[i] > min and arr[i] < max, then update min := arr[i – 1]
    • otherwise if arr[i] > min and arr[i] < max, then update max := arr[i]
    • if none of these are valid, then element will be inserted into a new level, so break

Example

#include <iostream>
using namespace std;
bool canMakeBSTifHeightN(int arr[], int n) {
   int min = INT_MIN;
   int max = INT_MAX;
   for(int i = 1; i < n; i++){
      if (arr[i] > arr[i - 1] && arr[i] > min && arr[i] < max) {
         min = arr[i - 1];
      } else if (arr[i] < arr[i - 1] && arr[i] > min && arr[i] <
      max) {
         max = arr[i - 1];
      } else {
         return true;
      }
   }
   return false;
}
int main() {
   int elements[] = {50, 30, 20, 25, 10};
   int n = sizeof(elements)/sizeof(elements[0]);
   if (canMakeBSTifHeightN(elements, n))
      cout << "We can make BST of height " << n;
   else
      cout << "We can not make BST of height " << n;
}

Output

We can make BST of height 5

Updated on: 21-Oct-2019

33 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements