Check if the given array can represent Level Order Traversal of Binary Search Tree
Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
53 Likes
Like
Report
Given an array of size n. The task is to check whether the given array can represent the level order traversal of a Binary Search Tree or not.
Examples:
Input: arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10} Output: True Explanation: For the given arr[] the Binary Search Tree is:
Input: arr[] = {11, 6, 13, 5, 12, 10} Output: False Explanation: The given arr[] do not represent the level order traversal of a BST.
Approach:
The idea is to use a queue to perform level order traversal. Push the first value in array (which will be the root in binary tree) along with two variables, start (initially set to -infinity) and end (initially set to infinity) to store the lower limit and upper limit of the tree/ subtree. Set index = 1. While queue is not empty, for each node, check if the current element in array lies between the range [start, node-1]. If it does, then add this value to queue and increment the index. Check if the current element in array lies in the range [node+1, end]. If it does, add the current node to the queueand increment the index. Once queue is empty, return true if index is equal to size of array. Otherwise return false.
Step by step approach:
Create a queue which takes objects of class Data (node, start, end). node key stores the value of the node, start key will store the lower bound of the subtree and end key will store the upper bound of the subtree.
Push the first value in array into the queue with start = -infinity and end = infinity. Create a variable index (initially set to 1).
While queue is not empty and index is less than size of array, perform the following steps:
Pop the node, start, end from the front of the queue.
Check if the current value in the array can be inserted into the left subtree of current node (if start<= value < node). If yes, then push [value, start, node-1] into the queue and increment the index.
If index is less than size of array and current value can be inserted in the right subtree of the current node (if node < value <= end). Then push [value, node+1, end] into the queue and increment the index.
Return true if the index is equal to size of array. Otherwise return false.
Below is the implementation of the above approach:
C++
// C++ implementation to check if the given array // can represent Level Order Traversal of Binary // Search Tree#include<bits/stdc++.h>usingnamespacestd;// Class to store node value, and// its lower and upper subtree range.classData{public:intnode,start,end;Data(intx,inty,intz){node=x;start=y;end=z;}};// function to check if the given array // can represent Level Order Traversal // of Binary Search TreeboollevelOrderIsOfBST(vector<int>arr){intn=arr.size();// if tree is emptyif(n==0)returntrue;queue<Data*>q;q.push(newData(arr[0],INT_MIN,INT_MAX));intindex=1;// until there are no more elements // in arr[] or queue is not emptywhile(index!=n&&!q.empty()){Data*front=q.front();q.pop();intnode=front->node,start=front->start,end=front->end;// if the current value in the array // can be inserted into the left // subtree of current nodeif(start<=arr[index]&&arr[index]<node){q.push(newData(arr[index],start,node-1));index++;}// if current value can be inserted in // the right subtree of the current nodeif(index<n&&node<arr[index]&&arr[index]<=end){q.push(newData(arr[index],node+1,end));index++;}}// given array represents level// order traversal of BSTif(index==n)returntrue;// given array do not represent // level order traversal of BST returnfalse;}intmain(){vector<int>arr={7,4,12,3,6,8,1,5,10};if(levelOrderIsOfBST(arr))cout<<"True";elsecout<<"False";return0;}
Java
// Java implementation to check if the given array // can represent Level Order Traversal of Binary // Search Treeimportjava.util.*;classData{intnode,start,end;Data(intx,inty,intz){node=x;start=y;end=z;}}classGfG{// function to check if the given array // can represent Level Order Traversal // of Binary Search TreestaticbooleanlevelOrderIsOfBST(ArrayList<Integer>arr){intn=arr.size();// if tree is emptyif(n==0){returntrue;}Queue<Data>q=newLinkedList<>();q.add(newData(arr.get(0),Integer.MIN_VALUE,Integer.MAX_VALUE));intindex=1;// until there are no more elements // in arr[] or queue is not emptywhile(index!=n&&!q.isEmpty()){Datafront=q.poll();intnode=front.node,start=front.start,end=front.end;// if the current value in the array // can be inserted into the left // subtree of current nodeif(start<=arr.get(index)&&arr.get(index)<node){q.add(newData(arr.get(index),start,node-1));index++;}// if current value can be inserted in // the right subtree of the current nodeif(index<n&&node<arr.get(index)&&arr.get(index)<=end){q.add(newData(arr.get(index),node+1,end));index++;}}// given array represents level// order traversal of BSTif(index==n){returntrue;}// given array does not represent // level order traversal of BST returnfalse;}publicstaticvoidmain(String[]args){ArrayList<Integer>arr=newArrayList<>();arr.add(7);arr.add(4);arr.add(12);arr.add(3);arr.add(6);arr.add(8);arr.add(1);arr.add(5);arr.add(10);if(levelOrderIsOfBST(arr))System.out.println("True");elseSystem.out.println("False");}}
Python
# Python implementation to check if the given array # can represent Level Order Traversal of Binary # Search TreeimportsysfromcollectionsimportdequeclassData:def__init__(self,x,y,z):self.node=xself.start=yself.end=z# function to check if the given array # can represent Level Order Traversal # of Binary Search TreedeflevelOrderIsOfBST(arr):n=len(arr)# if tree is emptyifn==0:returnTrueq=deque()q.append(Data(arr[0],-sys.maxsize,sys.maxsize))index=1# until there are no more elements # in arr[] or queue is not emptywhileindex!=nandq:front=q.popleft()node,start,end=front.node,front.start,front.end# if the current value in the array # can be inserted into the left # subtree of current nodeifstart<=arr[index]<node:q.append(Data(arr[index],start,node-1))index+=1# if current value can be inserted in # the right subtree of the current nodeifindex<nandnode<arr[index]<=end:q.append(Data(arr[index],node+1,end))index+=1# given array represents level# order traversal of BSTreturnindex==nif__name__=="__main__":arr=[7,4,12,3,6,8,1,5,10]iflevelOrderIsOfBST(arr):print("True")else:print("False")
C#
// C# implementation to check if the given array // can represent Level Order Traversal of Binary // Search TreeusingSystem;usingSystem.Collections.Generic;publicclassData{publicintnode,start,end;publicData(intx,inty,intz){node=x;start=y;end=z;}}classGfG{// function to check if the given array // can represent Level Order Traversal // of Binary Search TreestaticboollevelOrderIsOfBST(List<int>arr){intn=arr.Count;// if tree is emptyif(n==0){returntrue;}Queue<Data>q=newQueue<Data>();q.Enqueue(newData(arr[0],int.MinValue,int.MaxValue));intindex=1;// until there are no more elements // in arr[] or queue is not emptywhile(index!=n&&q.Count>0){Datafront=q.Dequeue();intnode=front.node,start=front.start,end=front.end;// if the current value in the array // can be inserted into the left // subtree of current nodeif(start<=arr[index]&&arr[index]<node){q.Enqueue(newData(arr[index],start,node-1));index++;}// if current value can be inserted in // the right subtree of the current nodeif(index<n&&node<arr[index]&&arr[index]<=end){q.Enqueue(newData(arr[index],node+1,end));index++;}}// given array represents level// order traversal of BSTreturnindex==n;}staticvoidMain(string[]args){List<int>arr=newList<int>{7,4,12,3,6,8,1,5,10};if(levelOrderIsOfBST(arr))Console.WriteLine("True");elseConsole.WriteLine("False");}}
JavaScript
// JavaScript implementation to check if the given array // can represent Level Order Traversal of Binary // Search TreeclassData{constructor(x,y,z){this.node=x;this.start=y;this.end=z;}}// function to check if the given array // can represent Level Order Traversal // of Binary Search TreefunctionlevelOrderIsOfBST(arr){letn=arr.length;// if tree is emptyif(n===0){returntrue;}letq=[];q.push(newData(arr[0],-Infinity,Infinity));letindex=1;// until there are no more elements // in arr[] or queue is not emptywhile(index!==n&&q.length>0){letfront=q.shift();letnode=front.node,start=front.start,end=front.end;// if the current value in the array // can be inserted into the left // subtree of current nodeif(start<=arr[index]&&arr[index]<node){q.push(newData(arr[index],start,node-1));index++;}// if current value can be inserted in // the right subtree of the current nodeif(index<n&&node<arr[index]&&arr[index]<=end){q.push(newData(arr[index],node+1,end));index++;}}// given array represents level// order traversal of BSTreturnindex===n;}letarr=[7,4,12,3,6,8,1,5,10];if(levelOrderIsOfBST(arr)){console.log("True");}else{console.log("False");}
Output
True
Time complexity: O(n), because we are iterating over the given array of size n only once. Auxiliary Space: O(n)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.