Check given array of size n can represent BST of n levels or not
Last Updated :
09 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.
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.
[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:
C++
// C++ program to Check given array
// can represent BST or not
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
// To create a Tree with n levels. We always
// insert new node to left if it is less than
// previous value.
Node *createNLevelTree(vector<int> arr, int n) {
Node *root = new Node(arr[0]);
Node *curr = root;
for (int i = 1; i < n; i++) {
if (curr->data > arr[i]) {
curr->left = new Node(arr[i]);
curr = curr->left;
}
else {
curr->right = new Node(arr[i]);
curr = curr->right;
}
}
return root;
}
// Function to check is binary tree is
// BST or not.
bool isBST(Node *root, int mini, int maxi) {
if (root == nullptr)
return true;
// If current node is out of range,
// return false.
if (root->data < mini || root->data > maxi)
return false;
// Check for left and right subtree.
return isBST(root->left, mini, root->data - 1)
&& isBST(root->right, root->data + 1, maxi);
}
// Returns true if given array of size n can
// represent a BST of n levels.
bool isNLevelBST(vector<int> arr, int n) {
// Construct the binary tree.
Node *root = createNLevelTree(arr, n);
// Check if the binary tree is BST.
return isBST(root, INT_MIN, INT_MAX);
}
int main() {
vector<int> arr = {512, 330, 78, 11, 8};
int n = 5;
if (isNLevelBST(arr, n))
cout << "True";
else
cout << "False";
return 0;
}
C
// C program to Check given array
// can represent BST or not
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int x);
// To create a Tree with n levels. We always
// insert new node to left if it is less than
// previous value.
struct Node* createNLevelTree(int arr[], int n) {
struct Node* root = createNode(arr[0]);
struct Node* curr = root;
for (int i = 1; i < n; i++) {
if (curr->data > arr[i]) {
curr->left = createNode(arr[i]);
curr = curr->left;
}
else {
curr->right = createNode(arr[i]);
curr = curr->right;
}
}
return root;
}
// Function to check is binary tree is
// BST or not.
int isBST(struct Node* root, int mini, int maxi) {
if (root == NULL)
return 1;
// If current node is out of range,
// return false.
if (root->data < mini || root->data > maxi)
return 0;
// Check for left and right subtree.
return isBST(root->left, mini, root->data - 1) &&
isBST(root->right, root->data + 1, maxi);
}
// Returns true if given array of size n can
// represent a BST of n levels.
int isNLevelBST(int arr[], int n) {
// Construct the binary tree.
struct Node* root = createNLevelTree(arr, n);
// Check if the binary tree is BST.
return isBST(root, INT_MIN, INT_MAX);
}
struct Node* createNode(int x) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = x;
node->left = NULL;
node->right = NULL;
return node;
}
int main() {
int arr[] = { 512, 330, 78, 11, 8 };
int n = 5;
if (isNLevelBST(arr, n))
printf("True\n");
else
printf("False\n");
return 0;
}
Java
// Java program to Check given array
// can represent BST or not
import java.util.ArrayList;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// To create a Tree with n levels. We always
// insert new node to left if it is less than
// previous value.
static Node createNLevelTree(ArrayList<Integer> arr, int n) {
Node root = new Node(arr.get(0));
Node curr = root;
for (int i = 1; i < n; i++) {
if (curr.data > arr.get(i)) {
curr.left = new Node(arr.get(i));
curr = curr.left;
} else {
curr.right = new Node(arr.get(i));
curr = curr.right;
}
}
return root;
}
// Function to check is binary tree is
// BST or not.
static boolean isBST(Node root, int mini, int maxi) {
if (root == null)
return true;
// If current node is out of range,
// return false.
if (root.data < mini || root.data > maxi)
return false;
// Check for left and right subtree.
return isBST(root.left, mini, root.data - 1) &&
isBST(root.right, root.data + 1, maxi);
}
// Returns true if given array of size n can
// represent a BST of n levels.
static boolean isNLevelBST(ArrayList<Integer> arr, int n) {
// Construct the binary tree.
Node root = createNLevelTree(arr, n);
// Check if the binary tree is BST.
return isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(512);
arr.add(330);
arr.add(78);
arr.add(11);
arr.add(8);
int n = 5;
if (isNLevelBST(arr, n))
System.out.println("True");
else
System.out.println("False");
}
}
Python
# Python program to Check given array
# can represent BST or not
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# To create a Tree with n levels. We always
# insert new node to left if it is less than
# previous value.
def createNLevelTree(arr, n):
root = Node(arr[0])
curr = root
for i in range(1, n):
if curr.data > arr[i]:
curr.left = Node(arr[i])
curr = curr.left
else:
curr.right = Node(arr[i])
curr = curr.right
return root
# Function to check is binary tree is
# BST or not.
def isBST(root, mini, maxi):
if root is None:
return True
# If current node is out of range,
# return False.
if root.data < mini or root.data > maxi:
return False
# Check for left and right subtree.
return isBST(root.left, mini, root.data - 1) and \
isBST(root.right, root.data + 1, maxi)
# Returns True if given array of size n can
# represent a BST of n levels.
def isNLevelBST(arr, n):
# Construct the binary tree.
root = createNLevelTree(arr, n)
# Check if the binary tree is BST.
return isBST(root, float('-inf'), float('inf'))
if __name__ == "__main__":
arr = [512, 330, 78, 11, 8]
n = 5
if isNLevelBST(arr, n):
print("True")
else:
print("False")
C#
// C# program to Check given array
// can represent BST or not
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// To create a Tree with n levels. We always
// insert new node to left if it is less than
// previous value.
static Node createNLevelTree(List<int> arr, int n) {
Node root = new Node(arr[0]);
Node curr = root;
for (int i = 1; i < n; i++) {
if (curr.data > arr[i]) {
curr.left = new Node(arr[i]);
curr = curr.left;
} else {
curr.right = new Node(arr[i]);
curr = curr.right;
}
}
return root;
}
// Function to check is binary tree is
// BST or not.
static bool isBST(Node root, int mini, int maxi) {
if (root == null)
return true;
// If current node is out of range,
// return false.
if (root.data < mini || root.data > maxi)
return false;
// Check for left and right subtree.
return isBST(root.left, mini, root.data - 1) &&
isBST(root.right, root.data + 1, maxi);
}
// Returns true if given array of size n can
// represent a BST of n levels.
static bool isNLevelBST(List<int> arr, int n) {
// Construct the binary tree.
Node root = createNLevelTree(arr, n);
// Check if the binary tree is BST.
return isBST(root, int.MinValue, int.MaxValue);
}
static void Main() {
List<int> arr = new List<int> { 512, 330, 78, 11, 8 };
int n = 5;
if (isNLevelBST(arr, n))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
// JavaScript program to Check given array
// can represent BST or not
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// To create a Tree with n levels. We always
// insert new node to left if it is less than
// previous value.
function createNLevelTree(arr, n) {
let root = new Node(arr[0]);
let curr = root;
for (let i = 1; i < n; i++) {
if (curr.data > arr[i]) {
curr.left = new Node(arr[i]);
curr = curr.left;
} else {
curr.right = new Node(arr[i]);
curr = curr.right;
}
}
return root;
}
// Function to check is binary tree is
// BST or not.
function isBST(root, mini, maxi) {
if (root === null) return true;
// If current node is out of range,
// return false.
if (root.data < mini || root.data > maxi)
return false;
// Check for left and right subtree.
return isBST(root.left, mini, root.data - 1) &&
isBST(root.right, root.data + 1, maxi);
}
// Returns true if given array of size n can
// represent a BST of n levels.
function isNLevelBST(arr, n) {
// Construct the binary tree.
let root = createNLevelTree(arr, n);
// Check if the binary tree is BST.
return isBST(root, -Infinity, Infinity);
}
let arr = [512, 330, 78, 11, 8];
let n = 5;
if (isNLevelBST(arr, n))
console.log("True");
else
console.log("False");
[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:
C++
// C++ program to Check given array
// can represent BST or not
#include <bits/stdc++.h>
using namespace std;
// Returns true if given array of size n can
// represent a BST of n levels.
bool isNLevelBST(vector<int> arr, int n) {
// set the range
int mini = INT_MIN, maxi = INT_MAX;
for (int i = 0; i < n; i++) {
// If current value is out
// of range
if (arr[i] < mini || arr[i] > maxi)
return false;
// Update maximum value of range
if (i + 1 < n && arr[i + 1] < arr[i]) {
maxi = arr[i] - 1;
}
// Update minimum value of range
else if (i + 1 < n && arr[i + 1] > arr[i]) {
mini = arr[i] + 1;
}
}
return true;
}
int main() {
vector<int> arr = {512, 330, 78, 11, 8};
int n = 5;
if (isNLevelBST(arr, n))
cout << "True";
else
cout << "False";
return 0;
}
C
// C program to Check given array
// can represent BST or not
#include <stdio.h>
#include <limits.h>
// Returns true if given array of size n can
// represent a BST of n levels.
int isNLevelBST(int arr[], int n) {
// set the range
int mini = INT_MIN, maxi = INT_MAX;
for (int i = 0; i < n; i++) {
// If current value is out
// of range
if (arr[i] < mini || arr[i] > maxi)
return 0;
// Update maximum value of range
if (i + 1 < n && arr[i + 1] < arr[i]) {
maxi = arr[i] - 1;
}
// Update minimum value of range
else if (i + 1 < n && arr[i + 1] > arr[i]) {
mini = arr[i] + 1;
}
}
return 1;
}
int main() {
int arr[] = { 512, 330, 78, 11, 8 };
int n = 5;
if (isNLevelBST(arr, n))
printf("True");
else
printf("False");
return 0;
}
Java
// Java program to Check given array
// can represent BST or not
import java.util.ArrayList;
class GfG {
// Returns true if given array of size n can
// represent a BST of n levels.
static boolean isNLevelBST(ArrayList<Integer> arr, int n) {
// set the range
int mini = Integer.MIN_VALUE, maxi = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
// If current value is out
// of range
if (arr.get(i) < mini || arr.get(i) > maxi)
return false;
// Update maximum value of range
if (i + 1 < n && arr.get(i + 1) < arr.get(i)) {
maxi = arr.get(i) - 1;
}
// Update minimum value of range
else if (i + 1 < n && arr.get(i + 1) > arr.get(i)) {
mini = arr.get(i) + 1;
}
}
return true;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(512);
arr.add(330);
arr.add(78);
arr.add(11);
arr.add(8);
int n = 5;
if (isNLevelBST(arr, n))
System.out.println("True");
else
System.out.println("False");
}
}
Python
# Python program to Check given array
# can represent BST or not
# Returns true if given array of size n can
# represent a BST of n levels.
def isNLevelBST(arr, n):
# set the range
mini = float('-inf')
maxi = float('inf')
for i in range(n):
# If current value is out
# of range
if arr[i] < mini or arr[i] > maxi:
return False
# Update maximum value of range
if i + 1 < n and arr[i + 1] < arr[i]:
maxi = arr[i] - 1
# Update minimum value of range
elif i + 1 < n and arr[i + 1] > arr[i]:
mini = arr[i] + 1
return True
if __name__ == "__main__":
arr = [512, 330, 78, 11, 8]
n = 5
if isNLevelBST(arr, n):
print("True")
else:
print("False")
C#
// C# program to Check given array
// can represent BST or not
using System;
using System.Collections.Generic;
class GfG {
// Returns true if given array of size n can
// represent a BST of n levels.
static bool isNLevelBST(List<int> arr, int n) {
// set the range
int mini = int.MinValue, maxi = int.MaxValue;
for (int i = 0; i < n; i++) {
// If current value is out
// of range
if (arr[i] < mini || arr[i] > maxi)
return false;
// Update maximum value of range
if (i + 1 < n && arr[i + 1] < arr[i]) {
maxi = arr[i] - 1;
}
// Update minimum value of range
else if (i + 1 < n && arr[i + 1] > arr[i]) {
mini = arr[i] + 1;
}
}
return true;
}
static void Main() {
List<int> arr = new List<int> { 512, 330, 78, 11, 8 };
int n = 5;
if (isNLevelBST(arr, n))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
// JavaScript program to Check given array
// can represent BST or not
// Returns true if given array of size n can
// represent a BST of n levels.
function isNLevelBST(arr, n) {
// set the range
let mini = Number.MIN_SAFE_INTEGER, maxi = Number.MAX_SAFE_INTEGER;
for (let i = 0; i < n; i++) {
// If current value is out
// of range
if (arr[i] < mini || arr[i] > maxi)
return false;
// Update maximum value of range
if (i + 1 < n && arr[i + 1] < arr[i]) {
maxi = arr[i] - 1;
}
// Update minimum value of range
else if (i + 1 < n && arr[i + 1] > arr[i]) {
mini = arr[i] + 1;
}
}
return true;
}
let arr = [512, 330, 78, 11, 8];
let n = 5;
if (isNLevelBST(arr, n))
console.log("True");
else
console.log("False");
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem