Skip to content
Related Articles

Related Articles

Check if the given array can represent Level Order Traversal of Binary Search Tree

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 20 Jul, 2022
Improve Article
Save Article

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:

  1. Pop NodeDetails from the queue in temp.
  2. 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[].
  3. 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[].
  4. 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++




// C++ implementation to check if the given array
// can represent Level Order Traversal of Binary
// Search Tree
#include <bits/stdc++.h>
 
using namespace std;
 
// to store details of a node like
// node's data, 'min' and 'max' to obtain the
// range of values where node's left and
// right child's should lie
struct NodeDetails
{
    int data;
    int min, max;
};
 
// function to check if the given array
// can represent Level Order Traversal
// of Binary Search Tree
bool levelOrderIsOfBST(int arr[], int n)
{
    // if tree is empty
    if (n == 0)
        return true;
     
    // queue to store NodeDetails
    queue<NodeDetails> q;
     
    // index variable to access array elements
    int i=0;
     
    // node details for the
    // root of the BST
    NodeDetails newNode;
    newNode.data = arr[i++];
    newNode.min = INT_MIN;
    newNode.max = INT_MAX;
    q.push(newNode);
     
    // until there are no more elements
    // in arr[] or queue is not empty
    while (i != n && !q.empty())       
    {
        // extracting NodeDetails of a
        // node from the queue
        NodeDetails temp = q.front();
        q.pop();
         
        // check whether there are more elements
        // in the arr[] and arr[i] can be left child
        // of 'temp.data' or not
        if (i < n && (arr[i] < temp.data &&
                     arr[i] > temp.min))
        {
            // Create NodeDetails for newNode
            /// and add it to the queue
            newNode.data = arr[i++];
            newNode.min = temp.min;
            newNode.max = temp.data;
            q.push(newNode);               
        }
         
        // check whether there are more elements
        // in the arr[] and arr[i] can be right child
        // of 'temp.data' or not
        if (i < n && (arr[i] > temp.data &&
                      arr[i] < temp.max))
        {
            // Create NodeDetails for newNode
            /// and add it to the queue
            newNode.data = arr[i++];
            newNode.min = temp.data;
            newNode.max = temp.max;
            q.push(newNode);           
        }       
    }
     
    // given array represents level
    // order traversal of BST
    if (i == n)
        return true;
         
    // given array do not represent
    // level order traversal of BST   
    return false;       
}
 
// Driver program to test above
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




// Java implementation to check if the given array
// can represent Level Order Traversal of Binary
// Search Tree
import java.util.*;
 
class Solution
{
 
// to store details of a node like
// node's data, 'min' and 'max' to obtain the
// range of values where node's left and
// right child's should lie
static class NodeDetails
{
    int data;
    int min, max;
};
 
// function to check if the given array
// can represent Level Order Traversal
// of Binary Search Tree
static boolean levelOrderIsOfBST(int arr[], int n)
{
    // if tree is empty
    if (n == 0)
        return true;
     
    // queue to store NodeDetails
    Queue<NodeDetails> q = new LinkedList<NodeDetails>();
     
    // index variable to access array elements
    int i = 0;
     
    // node details for the
    // root of the BST
    NodeDetails newNode=new NodeDetails();
    newNode.data = arr[i++];
    newNode.min = Integer.MIN_VALUE;
    newNode.max = Integer.MAX_VALUE;
    q.add(newNode);
     
    // until there are no more elements
    // in arr[] or queue is not empty
    while (i != n && q.size() > 0)    
    {
        // extracting NodeDetails of a
        // node from the queue
        NodeDetails temp = q.peek();
        q.remove();
        newNode = new NodeDetails();
         
        // check whether there are more elements
        // in the arr[] and arr[i] can be left child
        // of 'temp.data' or not
        if (i < n && (arr[i] < (int)temp.data &&
                    arr[i] > (int)temp.min))
        {
            // Create NodeDetails for newNode
            /// and add it to the queue
            newNode.data = arr[i++];
            newNode.min = temp.min;
            newNode.max = temp.data;
            q.add(newNode);            
        }
         
        newNode=new NodeDetails();
         
        // check whether there are more elements
        // in the arr[] and arr[i] can be right child
        // of 'temp.data' or not
        if (i < n && (arr[i] > (int)temp.data &&
                    arr[i] < (int)temp.max))
        {
            // Create NodeDetails for newNode
            /// and add it to the queue
            newNode.data = arr[i++];
            newNode.min = temp.data;
            newNode.max = temp.max;
            q.add(newNode);        
        }    
    }
     
    // given array represents level
    // order traversal of BST
    if (i == n)
        return true;
         
    // given array do not represent
    // level order traversal of BST
    return false;    
}
 
// Driver code
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");    
     
}
}
 
// This code is contributed by Arnab Kundu

Python3




# Python3 implementation to check if the
# given array can represent Level Order
# Traversal of Binary Search Tree
INT_MIN, INT_MAX = float('-inf'), float('inf')
 
# To store details of a node like node's
# data, 'min' and 'max' to obtain the
# range of values where node's left
# and right child's should lie
class NodeDetails:
 
    def __init__(self, data, min, max):
        self.data = data
        self.min = min
        self.max = max
 
# function to check if the given array
# can represent Level Order Traversal
# of Binary Search Tree
def levelOrderIsOfBST(arr, n):
 
    # if tree is empty
    if n == 0:
        return True
     
    # queue to store NodeDetails
    q = []
     
    # index variable to access array elements
    i = 0
     
    # node details for the root of the BST
    newNode = NodeDetails(arr[i], INT_MIN, INT_MAX)
    i += 1
    q.append(newNode)
     
    # until there are no more elements
    # in arr[] or queue is not empty
    while i != n and len(q) != 0:    
     
        # extracting NodeDetails of a
        # node from the queue
        temp = q.pop(0)
         
        # check whether there are more elements
        # in the arr[] and arr[i] can be left
        # child of 'temp.data' or not
        if i < n and (arr[i] < temp.data and
                    arr[i] > temp.min):
         
            # Create NodeDetails for newNode
            #/ and add it to the queue
            newNode = NodeDetails(arr[i], temp.min, temp.data)
            i += 1
            q.append(newNode)            
         
        # check whether there are more elements
        # in the arr[] and arr[i] can be right
        # child of 'temp.data' or not
        if i < n and (arr[i] > temp.data and
                    arr[i] < temp.max):
         
            # Create NodeDetails for newNode
            #/ and add it to the queue
            newNode = NodeDetails(arr[i], temp.data, temp.max)
            i += 1
            q.append(newNode)        
                 
    # given array represents level
    # order traversal of BST
    if i == n:
        return True
         
    # given array do not represent
    # level order traversal of BST
    return False       
 
# Driver code
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")
 
# This code is contributed by Rituraj Jain

C#




// C# implementation to check if the given array
// can represent Level Order Traversal of Binary
// Search Tree
using System;
using System.Collections.Generic;
     
class GFG
{
 
// to store details of a node like
// node's data, 'min' and 'max' to obtain the
// range of values where node's left and
// right child's should lie
public class NodeDetails
{
    public int data;
    public int min, max;
};
 
// function to check if the given array
// can represent Level Order Traversal
// of Binary Search Tree
static Boolean levelOrderIsOfBST(int []arr, int n)
{
    // if tree is empty
    if (n == 0)
        return true;
     
    // queue to store NodeDetails
    Queue<NodeDetails> q = new Queue<NodeDetails>();
     
    // index variable to access array elements
    int i = 0;
     
    // node details for the
    // root of the BST
    NodeDetails newNode=new NodeDetails();
    newNode.data = arr[i++];
    newNode.min = int.MinValue;
    newNode.max = int.MaxValue;
    q.Enqueue(newNode);
     
    // until there are no more elements
    // in arr[] or queue is not empty
    while (i != n && q.Count > 0)    
    {
        // extracting NodeDetails of a
        // node from the queue
        NodeDetails temp = q.Peek();
        q.Dequeue();
        newNode = new NodeDetails();
         
        // check whether there are more elements
        // in the arr[] and arr[i] can be left child
        // of 'temp.data' or not
        if (i < n && (arr[i] < (int)temp.data &&
                    arr[i] > (int)temp.min))
        {
            // Create NodeDetails for newNode
            /// and add it to the queue
            newNode.data = arr[i++];
            newNode.min = temp.min;
            newNode.max = temp.data;
            q.Enqueue(newNode);            
        }
         
        newNode=new NodeDetails();
         
        // check whether there are more elements
        // in the arr[] and arr[i] can be right child
        // of 'temp.data' or not
        if (i < n && (arr[i] > (int)temp.data &&
                    arr[i] < (int)temp.max))
        {
            // Create NodeDetails for newNode
            /// and add it to the queue
            newNode.data = arr[i++];
            newNode.min = temp.data;
            newNode.max = temp.max;
            q.Enqueue(newNode);        
        }    
    }
     
    // given array represents level
    // order traversal of BST
    if (i == n)
        return true;
         
    // given array do not represent
    // level order traversal of BST
    return false;    
}
 
// Driver code
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");    
     
}
}
 
// This code is contributed by Rajput-Ji

Javascript




<script>
 
// Javascript implementation to check if
// the given array can represent Level
// Order Traversal of Binary Search Tree
 
// To store details of a node like node's
// data, 'min' and 'max' to obtain the
// range of values where node's left and
// right child's should lie
class NodeDetails
{
    constructor()
    {
       this.min;
       this.max;
       this.data;
    }
}
 
// Function to check if the given array
// can represent Level Order Traversal
// of Binary Search Tree
function levelOrderIsOfBST(arr, n)
{
     
    // If tree is empty
    if (n == 0)
        return true;
 
    // Queue to store NodeDetails
    let q = [];
 
    // Index variable to access array elements
    let i = 0;
 
    // Node details for the
    // root of the BST
    let newNode = new NodeDetails();
    newNode.data = arr[i++];
    newNode.min = Number.MIN_VALUE;
    newNode.max = Number.MAX_VALUE;
    q.push(newNode);
 
    // Until there are no more elements
    // in arr[] or queue is not empty
    while (i != n && q.length > 0)    
    {
         
        // Extracting NodeDetails of a
        // node from the queue
        let temp = q[0];
        q.shift();
        newNode = new NodeDetails();
 
        // Check whether there are more elements
        // in the arr[] and arr[i] can be left child
        // of 'temp.data' or not
        if (i < n && (arr[i] < temp.data &&
                      arr[i] > temp.min))
        {
             
            // Create NodeDetails for newNode
            // and add it to the queue
            newNode.data = arr[i++];
            newNode.min = temp.min;
            newNode.max = temp.data;
            q.push(newNode);            
        }
 
        newNode = new NodeDetails();
 
        // Check whether there are more elements
        // in the arr[] and arr[i] can be right child
        // of 'temp.data' or not
        if (i < n && (arr[i] > temp.data &&
                      arr[i] < temp.max))
        {
             
            // Create NodeDetails for newNode
            // and add it to the queue
            newNode.data = arr[i++];
            newNode.min = temp.data;
            newNode.max = temp.max;
            q.push(newNode);        
        }    
    }
 
    // Given array represents level
    // order traversal of BST
    if (i == n)
        return true;
 
    // Given array do not represent
    // level order traversal of BST
    return false;    
}
 
// Driver code
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");   
     
// This code is contributed by vaibhavrabadiya3
 
</script>

Output

Yes

Time Complexity: O(n)

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. 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!