Check if the given array can represent Level Order Traversal of Binary Search Tree
Last Updated :
14 Oct, 2024
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 queue and 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>
using namespace std;
// Class to store node value, and
// its lower and upper subtree range.
class Data {
public:
int node, start, end;
Data (int x, int y, int z) {
node = x;
start = y;
end = z;
}
};
// function to check if the given array
// can represent Level Order Traversal
// of Binary Search Tree
bool levelOrderIsOfBST(vector<int> arr) {
int n = arr.size();
// if tree is empty
if (n == 0)
return true;
queue<Data*> q;
q.push(new Data(arr[0], INT_MIN, INT_MAX));
int index = 1;
// until there are no more elements
// in arr[] or queue is not empty
while (index != n && !q.empty()) {
Data* front = q.front();
q.pop();
int node = front->node, start = front->start,
end = front->end;
// if the current value in the array
// can be inserted into the left
// subtree of current node
if (start <= arr[index] && arr[index] < node) {
q.push(new Data(arr[index], start, node-1));
index++;
}
// if current value can be inserted in
// the right subtree of the current node
if (index < n && node < arr[index] &&
arr[index] <= end) {
q.push(new Data(arr[index], node+1, end));
index++;
}
}
// given array represents level
// order traversal of BST
if (index == n)
return true;
// given array do not represent
// level order traversal of BST
return false;
}
int main() {
vector<int> arr = {7, 4, 12, 3, 6, 8, 1, 5, 10};
if (levelOrderIsOfBST(arr))
cout << "True";
else
cout << "False";
return 0;
}
Java
// Java implementation to check if the given array
// can represent Level Order Traversal of Binary
// Search Tree
import java.util.*;
class Data {
int node, start, end;
Data(int x, int y, int z) {
node = x;
start = y;
end = z;
}
}
class GfG {
// function to check if the given array
// can represent Level Order Traversal
// of Binary Search Tree
static boolean levelOrderIsOfBST
(ArrayList<Integer> arr) {
int n = arr.size();
// if tree is empty
if (n == 0) {
return true;
}
Queue<Data> q = new LinkedList<>();
q.add(new Data(arr.get(0), Integer.MIN_VALUE,
Integer.MAX_VALUE));
int index = 1;
// until there are no more elements
// in arr[] or queue is not empty
while (index != n && !q.isEmpty()) {
Data front = q.poll();
int node = front.node, start = front.start,
end = front.end;
// if the current value in the array
// can be inserted into the left
// subtree of current node
if (start <= arr.get(index) &&
arr.get(index) < node) {
q.add(new Data(arr.get(index), start, node - 1));
index++;
}
// if current value can be inserted in
// the right subtree of the current node
if (index < n && node < arr.get(index) &&
arr.get(index) <= end) {
q.add(new Data(arr.get(index), node + 1, end));
index++;
}
}
// given array represents level
// order traversal of BST
if (index == n) {
return true;
}
// given array does not represent
// level order traversal of BST
return false;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
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");
else
System.out.println("False");
}
}
Python
# Python implementation to check if the given array
# can represent Level Order Traversal of Binary
# Search Tree
import sys
from collections import deque
class Data:
def __init__(self, x, y, z):
self.node = x
self.start = y
self.end = z
# function to check if the given array
# can represent Level Order Traversal
# of Binary Search Tree
def levelOrderIsOfBST(arr):
n = len(arr)
# if tree is empty
if n == 0:
return True
q = deque()
q.append(Data(arr[0], -sys.maxsize, sys.maxsize))
index = 1
# until there are no more elements
# in arr[] or queue is not empty
while index != n and q:
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 node
if start <= 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 node
if index < n and node < arr[index] <= end:
q.append(Data(arr[index], node + 1, end))
index += 1
# given array represents level
# order traversal of BST
return index == n
if __name__ == "__main__":
arr = [7, 4, 12, 3, 6, 8, 1, 5, 10]
if levelOrderIsOfBST(arr):
print("True")
else:
print("False")
C#
// C# implementation to check if the given array
// can represent Level Order Traversal of Binary
// Search Tree
using System;
using System.Collections.Generic;
public class Data {
public int node, start, end;
public Data(int x, int y, int z) {
node = x;
start = y;
end = z;
}
}
class GfG {
// function to check if the given array
// can represent Level Order Traversal
// of Binary Search Tree
static bool levelOrderIsOfBST(List<int> arr) {
int n = arr.Count;
// if tree is empty
if (n == 0) {
return true;
}
Queue<Data> q = new Queue<Data>();
q.Enqueue(new Data(arr[0], int.MinValue,
int.MaxValue));
int index = 1;
// until there are no more elements
// in arr[] or queue is not empty
while (index != n && q.Count > 0) {
Data front = q.Dequeue();
int node = front.node, start = front.start,
end = front.end;
// if the current value in the array
// can be inserted into the left
// subtree of current node
if (start <= arr[index] && arr[index] < node) {
q.Enqueue(new Data(arr[index], start, node - 1));
index++;
}
// if current value can be inserted in
// the right subtree of the current node
if (index < n && node < arr[index]
&& arr[index] <= end) {
q.Enqueue(new Data(arr[index], node + 1, end));
index++;
}
}
// given array represents level
// order traversal of BST
return index == n;
}
static void Main(string[] args) {
List<int> arr = new List<int> { 7, 4, 12, 3, 6, 8, 1, 5, 10 };
if (levelOrderIsOfBST(arr))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
// JavaScript implementation to check if the given array
// can represent Level Order Traversal of Binary
// Search Tree
class Data {
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 Tree
function levelOrderIsOfBST(arr) {
let n = arr.length;
// if tree is empty
if (n === 0) {
return true;
}
let q = [];
q.push(new Data(arr[0], -Infinity, Infinity));
let index = 1;
// until there are no more elements
// in arr[] or queue is not empty
while (index !== n && q.length > 0) {
let front = q.shift();
let node = front.node, start = front.start,
end = front.end;
// if the current value in the array
// can be inserted into the left
// subtree of current node
if (start <= arr[index] && arr[index] < node) {
q.push(new Data(arr[index], start, node - 1));
index++;
}
// if current value can be inserted in
// the right subtree of the current node
if (index < n && node < arr[index] && arr[index] <= end) {
q.push(new Data(arr[index], node + 1, end));
index++;
}
}
// given array represents level
// order traversal of BST
return index === n;
}
let arr = [7, 4, 12, 3, 6, 8, 1, 5, 10];
if (levelOrderIsOfBST(arr)) {
console.log("True");
} else {
console.log("False");
}
Time complexity: O(n), because we are iterating over the given array of size n only once.
Auxiliary Space: O(n)
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem