Given an array of size n. The problem 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 : Yes
For the given arr[] the Binary Search Tree is:
7
/ \
4 12
/ \ /
3 6 8
/ / \
1 5 10
Input : arr[] = {11, 6, 13, 5, 12, 10}
Output : No
The given arr[] do not represent the level
order traversal of a BST.
The idea is to use a queue data structure. Every element of queue has a structure say NodeDetails which stores details of a tree node. The details are node’s data, and two variables min and max where min stores the lower limit for the node values which can be a part of the left subtree and max stores the upper limit for the node values which can be a part of the right subtree for the specified node in NodeDetails structure variable. For the 1st array value arr[0], create a NodeDetails structure having arr[0] as node’s data and min = INT_MIN and max = INT_MAX. Add this structure variable to the queue. This Node will be the root of the tree. Move to 2nd element in arr[] and then perform the following steps:
- Pop NodeDetails from the queue in temp.
- Check whether the current array element can be a left child of the node in temp with the help of min and temp.data values. If it can, then create a new NodeDetails structure for this new array element value with its proper ‘min’ and ‘max’ values and push it to the queue, and move to next element in arr[].
- Check whether the current array element can be a right child of the node in temp with the help of max and temp.data values. If it can, then create a new NodeDetails structure for this new array element value with its proper ‘min’ and ‘max’ values and push it to the queue, and move to next element in arr[].
- Repeat steps 1, 2 and 3 until there are no more elements in arr[] or there are no more elements in the queue.
Finally, if all the elements of the array have been traversed then the array represents the level order traversal of a BST, else NOT.
C++
#include <bits/stdc++.h>
using namespace std;
struct NodeDetails
{
int data;
int min, max;
};
bool levelOrderIsOfBST( int arr[], int n)
{
if (n == 0)
return true ;
queue<NodeDetails> q;
int i=0;
NodeDetails newNode;
newNode.data = arr[i++];
newNode.min = INT_MIN;
newNode.max = INT_MAX;
q.push(newNode);
while (i != n && !q.empty())
{
NodeDetails temp = q.front();
q.pop();
if (i < n && (arr[i] < temp.data &&
arr[i] > temp.min))
{
newNode.data = arr[i++];
newNode.min = temp.min;
newNode.max = temp.data;
q.push(newNode);
}
if (i < n && (arr[i] > temp.data &&
arr[i] < temp.max))
{
newNode.data = arr[i++];
newNode.min = temp.data;
newNode.max = temp.max;
q.push(newNode);
}
}
if (i == n)
return true ;
return false ;
}
int main()
{
int arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10};
int n = sizeof (arr) / sizeof (arr[0]);
if (levelOrderIsOfBST(arr, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
public class Solution
{
static class NodeDetails
{
int data;
int min, max;
};
static boolean levelOrderIsOfBST( int arr[], int n)
{
if (n == 0 )
return true ;
Queue<NodeDetails> q = new LinkedList<NodeDetails>();
int i = 0 ;
NodeDetails newNode= new NodeDetails();
newNode.data = arr[i++];
newNode.min = Integer.MIN_VALUE;
newNode.max = Integer.MAX_VALUE;
q.add(newNode);
while (i != n && q.size() > 0 )
{
NodeDetails temp = q.peek();
q.remove();
newNode = new NodeDetails();
if (i < n && (arr[i] < ( int )temp.data &&
arr[i] > ( int )temp.min))
{
newNode.data = arr[i++];
newNode.min = temp.min;
newNode.max = temp.data;
q.add(newNode);
}
newNode= new NodeDetails();
if (i < n && (arr[i] > ( int )temp.data &&
arr[i] < ( int )temp.max))
{
newNode.data = arr[i++];
newNode.min = temp.data;
newNode.max = temp.max;
q.add(newNode);
}
}
if (i == n)
return true ;
return false ;
}
public static void main(String args[])
{
int arr[] = { 7 , 4 , 12 , 3 , 6 , 8 , 1 , 5 , 10 };
int n = arr.length;
if (levelOrderIsOfBST(arr, n))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
INT_MIN, INT_MAX = float ( '-inf' ), float ( 'inf' )
class NodeDetails:
def __init__( self , data, min , max ):
self .data = data
self . min = min
self . max = max
def levelOrderIsOfBST(arr, n):
if n = = 0 :
return True
q = []
i = 0
newNode = NodeDetails(arr[i], INT_MIN, INT_MAX)
i + = 1
q.append(newNode)
while i ! = n and len (q) ! = 0 :
temp = q.pop( 0 )
if i < n and (arr[i] < temp.data and
arr[i] > temp. min ):
newNode = NodeDetails(arr[i], temp. min , temp.data)
i + = 1
q.append(newNode)
if i < n and (arr[i] > temp.data and
arr[i] < temp. max ):
newNode = NodeDetails(arr[i], temp.data, temp. max )
i + = 1
q.append(newNode)
if i = = n:
return True
return False
if __name__ = = "__main__" :
arr = [ 7 , 4 , 12 , 3 , 6 , 8 , 1 , 5 , 10 ]
n = len (arr)
if levelOrderIsOfBST(arr, n):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public class NodeDetails
{
public int data;
public int min, max;
};
static Boolean levelOrderIsOfBST( int []arr, int n)
{
if (n == 0)
return true ;
Queue<NodeDetails> q = new Queue<NodeDetails>();
int i = 0;
NodeDetails newNode= new NodeDetails();
newNode.data = arr[i++];
newNode.min = int .MinValue;
newNode.max = int .MaxValue;
q.Enqueue(newNode);
while (i != n && q.Count > 0)
{
NodeDetails temp = q.Peek();
q.Dequeue();
newNode = new NodeDetails();
if (i < n && (arr[i] < ( int )temp.data &&
arr[i] > ( int )temp.min))
{
/// and add it to the queue
newNode.data = arr[i++];
newNode.min = temp.min;
newNode.max = temp.data;
q.Enqueue(newNode);
}
newNode= new NodeDetails();
if (i < n && (arr[i] > ( int )temp.data &&
arr[i] < ( int )temp.max))
{
/// and add it to the queue
newNode.data = arr[i++];
newNode.min = temp.data;
newNode.max = temp.max;
q.Enqueue(newNode);
}
}
if (i == n)
return true ;
return false ;
}
public static void Main(String []args)
{
int []arr = {7, 4, 12, 3, 6, 8, 1, 5, 10};
int n = arr.Length;
if (levelOrderIsOfBST(arr, n))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
class NodeDetails
{
constructor()
{
this .min;
this .max;
this .data;
}
}
function levelOrderIsOfBST(arr, n)
{
if (n == 0)
return true ;
let q = [];
let i = 0;
let newNode = new NodeDetails();
newNode.data = arr[i++];
newNode.min = Number.MIN_VALUE;
newNode.max = Number.MAX_VALUE;
q.push(newNode);
while (i != n && q.length > 0)
{
let temp = q[0];
q.shift();
newNode = new NodeDetails();
if (i < n && (arr[i] < temp.data &&
arr[i] > temp.min))
{
newNode.data = arr[i++];
newNode.min = temp.min;
newNode.max = temp.data;
q.push(newNode);
}
newNode = new NodeDetails();
if (i < n && (arr[i] > temp.data &&
arr[i] < temp.max))
{
newNode.data = arr[i++];
newNode.min = temp.data;
newNode.max = temp.max;
q.push(newNode);
}
}
if (i == n)
return true ;
return false ;
}
let arr = [ 7, 4, 12, 3, 6, 8, 1, 5, 10 ];
let n = arr.length;
if (levelOrderIsOfBST(arr, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time complexity: O(n), the time complexity of this algorithm is O(n) because we are iterating over the given array of size n only once.
Space complexity: O(n), here we are using a queue to store the nodes of the given tree. So the space complexity of this algorithm is O(n) as we are storing all the nodes of the given tree in the queue.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.