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)
Similar Reads
Binary Search Tree A Binary Search Tree (or BST) is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right chi
3 min read
Introduction to Binary Search Tree Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
3 min read
Applications of BST Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward.The left subtree of a node contains only node
3 min read
Applications, Advantages and Disadvantages of Binary Search Tree A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
2 min read
Insertion in Binary Search Tree (BST) Given a BST, the task is to insert a new node in this BST.Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is fo
15 min read
Searching in Binary Search Tree (BST) Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
7 min read
Deletion in Binary Search Tree (BST) Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios:Case 1. Delete a Leaf Node in BSTDeletion in BSTCase 2. Delete a Node with Single Child in BSTDeleting a single child node is also simple in BST. Copy the child to the node and delete the node. Deletion
10 min read
Binary Search Tree (BST) Traversals â Inorder, Preorder, Post Order Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree. Input: A Binary Search TreeOutput: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 1
10 min read
Balance a Binary Search Tree Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height.Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height.Input: Output: Explanation: The above u
10 min read
Self-Balancing Binary Search Trees Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
4 min read