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.
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>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){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,intn){Node*root=newNode(arr[0]);Node*curr=root;for(inti=1;i<n;i++){if(curr->data>arr[i]){curr->left=newNode(arr[i]);curr=curr->left;}else{curr->right=newNode(arr[i]);curr=curr->right;}}returnroot;}// Function to check is binary tree is// BST or not.boolisBST(Node*root,intmini,intmaxi){if(root==nullptr)returntrue;// If current node is out of range,// return false.if(root->data<mini||root->data>maxi)returnfalse;// Check for left and right subtree.returnisBST(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.boolisNLevelBST(vector<int>arr,intn){// Construct the binary tree.Node*root=createNLevelTree(arr,n);// Check if the binary tree is BST.returnisBST(root,INT_MIN,INT_MAX);}intmain(){vector<int>arr={512,330,78,11,8};intn=5;if(isNLevelBST(arr,n))cout<<"True";elsecout<<"False";return0;}
C
// C program to Check given array// can represent BST or not#include<stdio.h>#include<limits.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};structNode*createNode(intx);// To create a Tree with n levels. We always// insert new node to left if it is less than// previous value.structNode*createNLevelTree(intarr[],intn){structNode*root=createNode(arr[0]);structNode*curr=root;for(inti=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;}}returnroot;}// Function to check is binary tree is // BST or not.intisBST(structNode*root,intmini,intmaxi){if(root==NULL)return1;// If current node is out of range,// return false.if(root->data<mini||root->data>maxi)return0;// Check for left and right subtree.returnisBST(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.intisNLevelBST(intarr[],intn){// Construct the binary tree.structNode*root=createNLevelTree(arr,n);// Check if the binary tree is BST.returnisBST(root,INT_MIN,INT_MAX);}structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->left=NULL;node->right=NULL;returnnode;}intmain(){intarr[]={512,330,78,11,8};intn=5;if(isNLevelBST(arr,n))printf("True\n");elseprintf("False\n");return0;}
Java
// Java program to Check given array// can represent BST or notimportjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// To create a Tree with n levels. We always// insert new node to left if it is less than// previous value.staticNodecreateNLevelTree(ArrayList<Integer>arr,intn){Noderoot=newNode(arr.get(0));Nodecurr=root;for(inti=1;i<n;i++){if(curr.data>arr.get(i)){curr.left=newNode(arr.get(i));curr=curr.left;}else{curr.right=newNode(arr.get(i));curr=curr.right;}}returnroot;}// Function to check is binary tree is // BST or not.staticbooleanisBST(Noderoot,intmini,intmaxi){if(root==null)returntrue;// If current node is out of range,// return false.if(root.data<mini||root.data>maxi)returnfalse;// Check for left and right subtree.returnisBST(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.staticbooleanisNLevelBST(ArrayList<Integer>arr,intn){// Construct the binary tree.Noderoot=createNLevelTree(arr,n);// Check if the binary tree is BST.returnisBST(root,Integer.MIN_VALUE,Integer.MAX_VALUE);}publicstaticvoidmain(String[]args){ArrayList<Integer>arr=newArrayList<>();arr.add(512);arr.add(330);arr.add(78);arr.add(11);arr.add(8);intn=5;if(isNLevelBST(arr,n))System.out.println("True");elseSystem.out.println("False");}}
Python
# Python program to Check given array# can represent BST or notclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# To create a Tree with n levels. We always# insert new node to left if it is less than# previous value.defcreateNLevelTree(arr,n):root=Node(arr[0])curr=rootforiinrange(1,n):ifcurr.data>arr[i]:curr.left=Node(arr[i])curr=curr.leftelse:curr.right=Node(arr[i])curr=curr.rightreturnroot# Function to check is binary tree is # BST or not.defisBST(root,mini,maxi):ifrootisNone:returnTrue# If current node is out of range,# return False.ifroot.data<miniorroot.data>maxi:returnFalse# Check for left and right subtree.returnisBST(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.defisNLevelBST(arr,n):# Construct the binary tree.root=createNLevelTree(arr,n)# Check if the binary tree is BST.returnisBST(root,float('-inf'),float('inf'))if__name__=="__main__":arr=[512,330,78,11,8]n=5ifisNLevelBST(arr,n):print("True")else:print("False")
C#
// C# program to Check given array// can represent BST or notusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// To create a Tree with n levels. We always// insert new node to left if it is less than// previous value.staticNodecreateNLevelTree(List<int>arr,intn){Noderoot=newNode(arr[0]);Nodecurr=root;for(inti=1;i<n;i++){if(curr.data>arr[i]){curr.left=newNode(arr[i]);curr=curr.left;}else{curr.right=newNode(arr[i]);curr=curr.right;}}returnroot;}// Function to check is binary tree is // BST or not.staticboolisBST(Noderoot,intmini,intmaxi){if(root==null)returntrue;// If current node is out of range,// return false.if(root.data<mini||root.data>maxi)returnfalse;// Check for left and right subtree.returnisBST(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.staticboolisNLevelBST(List<int>arr,intn){// Construct the binary tree.Noderoot=createNLevelTree(arr,n);// Check if the binary tree is BST.returnisBST(root,int.MinValue,int.MaxValue);}staticvoidMain(){List<int>arr=newList<int>{512,330,78,11,8};intn=5;if(isNLevelBST(arr,n))Console.WriteLine("True");elseConsole.WriteLine("False");}}
JavaScript
// JavaScript program to Check given array// can represent BST or notclassNode{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.functioncreateNLevelTree(arr,n){letroot=newNode(arr[0]);letcurr=root;for(leti=1;i<n;i++){if(curr.data>arr[i]){curr.left=newNode(arr[i]);curr=curr.left;}else{curr.right=newNode(arr[i]);curr=curr.right;}}returnroot;}// Function to check is binary tree is // BST or not.functionisBST(root,mini,maxi){if(root===null)returntrue;// If current node is out of range,// return false.if(root.data<mini||root.data>maxi)returnfalse;// Check for left and right subtree.returnisBST(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.functionisNLevelBST(arr,n){// Construct the binary tree.letroot=createNLevelTree(arr,n);// Check if the binary tree is BST.returnisBST(root,-Infinity,Infinity);}letarr=[512,330,78,11,8];letn=5;if(isNLevelBST(arr,n))console.log("True");elseconsole.log("False");
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:
C++
// C++ program to Check given array// can represent BST or not#include<bits/stdc++.h>usingnamespacestd;// Returns true if given array of size n can// represent a BST of n levels.boolisNLevelBST(vector<int>arr,intn){// set the rangeintmini=INT_MIN,maxi=INT_MAX;for(inti=0;i<n;i++){// If current value is out// of rangeif(arr[i]<mini||arr[i]>maxi)returnfalse;// Update maximum value of rangeif(i+1<n&&arr[i+1]<arr[i]){maxi=arr[i]-1;}// Update minimum value of rangeelseif(i+1<n&&arr[i+1]>arr[i]){mini=arr[i]+1;}}returntrue;}intmain(){vector<int>arr={512,330,78,11,8};intn=5;if(isNLevelBST(arr,n))cout<<"True";elsecout<<"False";return0;}
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.intisNLevelBST(intarr[],intn){// set the rangeintmini=INT_MIN,maxi=INT_MAX;for(inti=0;i<n;i++){// If current value is out // of rangeif(arr[i]<mini||arr[i]>maxi)return0;// Update maximum value of range if(i+1<n&&arr[i+1]<arr[i]){maxi=arr[i]-1;}// Update minimum value of rangeelseif(i+1<n&&arr[i+1]>arr[i]){mini=arr[i]+1;}}return1;}intmain(){intarr[]={512,330,78,11,8};intn=5;if(isNLevelBST(arr,n))printf("True");elseprintf("False");return0;}
Java
// Java program to Check given array// can represent BST or notimportjava.util.ArrayList;classGfG{// Returns true if given array of size n can// represent a BST of n levels.staticbooleanisNLevelBST(ArrayList<Integer>arr,intn){// set the rangeintmini=Integer.MIN_VALUE,maxi=Integer.MAX_VALUE;for(inti=0;i<n;i++){// If current value is out // of rangeif(arr.get(i)<mini||arr.get(i)>maxi)returnfalse;// 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 rangeelseif(i+1<n&&arr.get(i+1)>arr.get(i)){mini=arr.get(i)+1;}}returntrue;}publicstaticvoidmain(String[]args){ArrayList<Integer>arr=newArrayList<>();arr.add(512);arr.add(330);arr.add(78);arr.add(11);arr.add(8);intn=5;if(isNLevelBST(arr,n))System.out.println("True");elseSystem.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.defisNLevelBST(arr,n):# set the rangemini=float('-inf')maxi=float('inf')foriinrange(n):# If current value is out # of rangeifarr[i]<miniorarr[i]>maxi:returnFalse# Update maximum value of range ifi+1<nandarr[i+1]<arr[i]:maxi=arr[i]-1# Update minimum value of rangeelifi+1<nandarr[i+1]>arr[i]:mini=arr[i]+1returnTrueif__name__=="__main__":arr=[512,330,78,11,8]n=5ifisNLevelBST(arr,n):print("True")else:print("False")
C#
// C# program to Check given array// can represent BST or notusingSystem;usingSystem.Collections.Generic;classGfG{// Returns true if given array of size n can// represent a BST of n levels.staticboolisNLevelBST(List<int>arr,intn){// set the rangeintmini=int.MinValue,maxi=int.MaxValue;for(inti=0;i<n;i++){// If current value is out // of rangeif(arr[i]<mini||arr[i]>maxi)returnfalse;// Update maximum value of range if(i+1<n&&arr[i+1]<arr[i]){maxi=arr[i]-1;}// Update minimum value of rangeelseif(i+1<n&&arr[i+1]>arr[i]){mini=arr[i]+1;}}returntrue;}staticvoidMain(){List<int>arr=newList<int>{512,330,78,11,8};intn=5;if(isNLevelBST(arr,n))Console.WriteLine("True");elseConsole.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.functionisNLevelBST(arr,n){// set the rangeletmini=Number.MIN_SAFE_INTEGER,maxi=Number.MAX_SAFE_INTEGER;for(leti=0;i<n;i++){// If current value is out // of rangeif(arr[i]<mini||arr[i]>maxi)returnfalse;// Update maximum value of range if(i+1<n&&arr[i+1]<arr[i]){maxi=arr[i]-1;}// Update minimum value of rangeelseif(i+1<n&&arr[i+1]>arr[i]){mini=arr[i]+1;}}returntrue;}letarr=[512,330,78,11,8];letn=5;if(isNLevelBST(arr,n))console.log("True");elseconsole.log("False");