Check given array of size n can represent BST of n levels or not
Last Updated :
29 Dec, 2022
Given an array of size n, the task is to find whether array can represent a BST with n levels.
Since levels are n, we construct a tree in the following manner.
Assuming a number X,
- Number higher than X is on the right side
- Number lower than X is on the left side.
Note: during the insertion, we never go beyond a number already visited.
Examples:
Input : 500, 200, 90, 250, 100
Output : No
Input : 5123, 3300, 783, 1111, 890
Output : Yes
Explanation :
For the sequence 500, 200, 90, 250, 100 formed tree(in above image) can’t represent BST.
The sequence 5123, 3300, 783, 1111, 890 forms a binary search tree hence its a correct sequence.
Method 1: By constructing BST
We first insert all array values level by level in a Tree. To insert, we check if current value is less than previous value or greater. After constructing the tree, we check if the constructed tree is Binary Search Tree or not.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
struct Node *right, *left;
};
Node* newNode( int num)
{
Node* temp = new Node;
temp->key = num;
temp->left = NULL;
temp->right = NULL;
return temp;
}
Node* createNLevelTree( int arr[], int n)
{
Node* root = newNode(arr[0]);
Node* temp = root;
for ( int i = 1; i < n; i++) {
if (temp->key > arr[i]) {
temp->left = newNode(arr[i]);
temp = temp->left;
}
else {
temp->right = newNode(arr[i]);
temp = temp->right;
}
}
return root;
}
bool isBST(Node* root, int min, int max)
{
if (root == NULL)
return true ;
if (root->key < min || root->key > max)
return false ;
return (isBST(root->left, min,
(root->key) - 1)
&& isBST(root->right,
(root->key) + 1, max));
}
bool canRepresentNLevelBST( int arr[], int n)
{
Node* root = createNLevelTree(arr, n);
return isBST(root, INT_MIN, INT_MAX);
}
int main()
{
int arr[] = { 512, 330, 78, 11, 8 };
int n = sizeof (arr) / sizeof (arr[0]);
if (canRepresentNLevelBST(arr, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
public class GFG
{
static class Node
{
int key;
Node right, left;
};
static Node newNode( int num)
{
Node temp = new Node();
temp.key = num;
temp.left = null ;
temp.right = null ;
return temp;
}
static Node createNLevelTree( int arr[], int n)
{
Node root = newNode(arr[ 0 ]);
Node temp = root;
for ( int i = 1 ; i < n; i++)
{
if (temp.key > arr[i])
{
temp.left = newNode(arr[i]);
temp = temp.left;
}
else
{
temp.right = newNode(arr[i]);
temp = temp.right;
}
}
return root;
}
static boolean isBST(Node root, int min, int max)
{
if (root == null )
{
return true ;
}
if (root.key < min || root.key > max)
{
return false ;
}
return (isBST(root.left, min,
(root.key) - 1 )
&& isBST(root.right,
(root.key) + 1 , max));
}
static boolean canRepresentNLevelBST( int arr[], int n)
{
Node root = createNLevelTree(arr, n);
return isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public static void main(String[] args)
{
int arr[] = { 512 , 330 , 78 , 11 , 8 };
int n = arr.length;
if (canRepresentNLevelBST(arr, n))
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python
class newNode():
def __init__( self , data):
self .key = data
self .left = None
self .right = None
def createNLevelTree(arr, n):
root = newNode(arr[ 0 ])
temp = root
for i in range ( 1 , n):
if (temp.key > arr[i]):
temp.left = newNode(arr[i])
temp = temp.left
else :
temp.right = newNode(arr[i])
temp = temp.right
return root
def isBST(root, min , max ):
if (root = = None ):
return True
if (root.key < min or root.key > max ):
return False
return (isBST(root.left, min , (root.key) - 1 ) and
isBST(root.right,(root.key) + 1 , max ))
def canRepresentNLevelBST(arr, n):
root = createNLevelTree(arr, n)
return isBST(root, 0 , 2 * * 32 )
arr = [ 512 , 330 , 78 , 11 , 8 ]
n = len (arr)
if (canRepresentNLevelBST(arr, n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
public class Node
{
public int key;
public Node right, left;
};
static Node newNode( int num)
{
Node temp = new Node();
temp.key = num;
temp.left = null ;
temp.right = null ;
return temp;
}
static Node createNLevelTree( int []arr, int n)
{
Node root = newNode(arr[0]);
Node temp = root;
for ( int i = 1; i < n; i++)
{
if (temp.key > arr[i])
{
temp.left = newNode(arr[i]);
temp = temp.left;
}
else
{
temp.right = newNode(arr[i]);
temp = temp.right;
}
}
return root;
}
static bool isBST(Node root, int min, int max)
{
if (root == null )
{
return true ;
}
if (root.key < min || root.key > max)
{
return false ;
}
return (isBST(root.left, min,
(root.key) - 1) &&
isBST(root.right,
(root.key) + 1, max));
}
static bool canRepresentNLevelBST( int []arr, int n)
{
Node root = createNLevelTree(arr, n);
return isBST(root, int .MinValue, int .MaxValue);
}
public static void Main(String[] args)
{
int []arr = {512, 330, 78, 11, 8};
int n = arr.Length;
if (canRepresentNLevelBST(arr, n))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
<script>
class Node
{
constructor()
{
this .key = 0;
this .left = null ;
this .right = null ;
}
};
function newNode(num)
{
var temp = new Node();
temp.key = num;
temp.left = null ;
temp.right = null ;
return temp;
}
function createNLevelTree(arr, n)
{
var root = newNode(arr[0]);
var temp = root;
for ( var i = 1; i < n; i++)
{
if (temp.key > arr[i])
{
temp.left = newNode(arr[i]);
temp = temp.left;
}
else
{
temp.right = newNode(arr[i]);
temp = temp.right;
}
}
return root;
}
function isBST(root, min, max)
{
if (root == null )
{
return true ;
}
if (root.key < min || root.key > max)
{
return false ;
}
return (isBST(root.left, min,
(root.key) - 1) &&
isBST(root.right,
(root.key) + 1, max));
}
function canRepresentNLevelBST(arr, n)
{
var root = createNLevelTree(arr, n);
return isBST(root, -1000000000, 1000000000);
}
var arr = [512, 330, 78, 11, 8];
var n = arr.length;
if (canRepresentNLevelBST(arr, n))
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Time Complexity: O(n), we traverse the whole array to create a binary tree, and then traverse it again to check if it is a BST. Thus, the overall time complexity is O(n).
Auxiliary Space: O(n), because we store the complete binary tree in memory.
Method 2 (Array Based):
- Take two variables max = INT_MAX to mark the maximum limit for left subtree and min = INT_MIN to mark the minimum limit for right subtree.
- Loop from arr[1] to arr[n-1]
- for each element check
- If ( arr[i] > arr[i-1] && arr[i] > min && arr[i] < max ), update min = arr[i-1]
- Else if ( arr[i] min && arr[i] < max ), update max = arr[i]
- If none of the above two conditions hold, then element will not be inserted in a new level, so break.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 5123, 3300, 783, 1111, 890 };
int n = sizeof (arr) / sizeof (arr[0]);
int max = INT_MAX;
int min = INT_MIN;
bool flag = true ;
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 {
flag = false ;
break ;
}
}
if (flag) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
return 0;
}
|
Java
class Solution
{
public static void main(String args[])
{
int arr[] = { 5123 , 3300 , 783 , 1111 , 890 };
int n = arr.length;
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
boolean flag = true ;
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 {
flag = false ;
break ;
}
}
if (flag) {
System.out.println( "Yes" );
}
else {
System.out.println( "No" );
}
}
}
|
Python3
if __name__ = = '__main__' :
arr = [ 5123 , 3300 , 783 , 1111 , 890 ]
n = len (arr)
max = 2147483647
min = - 2147483648
flag = True
for i in range ( 1 ,n):
if (arr[i] > arr[i - 1 ] and
arr[i] > min and arr[i] < max ):
min = arr[i - 1 ]
elif (arr[i] < arr[i - 1 ] and
arr[i] > min and arr[i] < max ):
max = arr[i - 1 ]
else :
flag = False
break
if (flag):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
public class Solution
{
public static void Main( string [] args)
{
int [] arr = new int [] {5123, 3300, 783, 1111, 890};
int n = arr.Length;
int max = int .MaxValue;
int min = int .MinValue;
bool flag = true ;
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
{
flag = false ;
break ;
}
}
if (flag)
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
<script>
let arr = [ 5123, 3300, 783, 1111, 890 ];
let n = arr.length;
let max = Number.MAX_VALUE;
let min = Number.MIN_VALUE;
let flag = true ;
for (let 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 {
flag = false ;
break ;
}
}
if (flag)
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...