VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-given-array-of-size-n-can-represent-bst-of-n-levels-or-not/

⇱ Check given array of size n can represent BST of n levels or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 9 Oct, 2024

Given an array of size n, the task is to find whether the array can represent a BST with n levels. 
Since levels are n, we construct a tree in the following manner. 
Assuming a number X, 

  • A number higher than X is on the right side
  • A number lower than X is on the left side.

Examples:

Input : arr[] = {500, 200, 90, 250, 100}
Output : False
Explanation : For the sequence 500, 200, 90, 250, 100 formed tree(in below image) can't represent BST.


👁 Check-given-array-of-size-n-can-represent-BST-of-n-levels-or-not_1


Input: arr[] = {5123, 3300, 783, 1111, 890}
Output: True
Explanation: The sequence 5123, 3300, 783, 1111, 890 forms a binary search tree hence its a correct sequence.

👁 Check-given-array-of-size-n-can-represent-BST-of-n-levels-or-not-2

[Naive Approach] By Constructing Binary Search Tree - O(n) Time and O(n) Space

The idea is insert all array values level by level in a binary tree. For each node, if its value is less than previous node, then add it to left subtree. Otherwise, add it to right subtree. After constructing the tree, check if the Binary tree is BST or not.

Below is the implementation of the above approach:


Output
True

[Expected Approach] Using Iterative Method - O(n) Time and O(1) Space

The idea is to use two variables:maxi and mini to mark the range of the subtree (initially set to maximum integer value and min integer value). For each value, if its value is out of range, simply return false. If next value is less than current value, then set the value of maxi to (current value-1). Else set the value of mini to (current value+1). Then, move to the next element.

Below is the implementation of the above approach:


Output
True
Comment
Article Tags: