Construct the BST (Binary Search Tree) from its given level order traversal.
Examples:
Input : {7, 4, 12, 3, 6, 8, 1, 5, 10}
Output : 
BST: 
        7        
       / \       
      4   12      
     / \  /     
    3  6 8    
   /  /   \
  1   5   10
Approach : 
The idea is to make a struct element NodeDetails which contains a pointer to the node, minimum data and maximum data of the ancestor. Now perform the steps as follows: 
- Push the root node to the queue of type NodeDetails.
- Extract NodeDetails of a node from the queue and compare them with the minimum and maximum values.
- Check whether there are more elements in the arr[] and arr[i] can be left child of ‘temp.ptr’ or not.
- Check whether there are more elements in the arr[] and arr[i] can be the right child of ‘temp.ptr’ or not.
- End the loop when the queue becomes empty.
Below is the implementation of the above approach:
C++
| // C++ program to construct BST// using level order traversal#include <bits/stdc++.h>usingnamespacestd;// Node structure of a binary treestructNode {    intdata;    Node* right;    Node* left;    Node(intx)    {        data = x;        right = NULL;        left = NULL;    }};// Structure formed to store the// details of the ancestorstructNodeDetails {    Node* ptr;    intmin, max;};// Function for the preorder traversalvoidpreorderTraversal(Node* root){    if(!root)        return;    cout << root->data << " ";    // Traversing left child    preorderTraversal(root->left);    // Traversing right child    preorderTraversal(root->right);}// Function to make a new node// and return its pointerNode* getNode(intdata){    Node* temp = newNode(0);    temp->data = data;    temp->left = NULL;    temp->right = NULL;    returntemp;}// Function to construct the BSTNode* constructBst(intarr[], intn){    if(n == 0)        returnNULL;    Node* root;    queue<NodeDetails> q;    // index variable to    // access array elements    inti = 0;    // Node details for the    // root of the BST    NodeDetails newNode;    newNode.ptr = getNode(arr[i++]);    newNode.min = INT_MIN;    newNode.max = INT_MAX;    q.push(newNode);    // Getting the root of the BST    root = newNode.ptr;    // Until there are no more    // elements in arr[]    while(i != n) {        // 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.ptr' or not        if(i < n            && (arr[i] < temp.ptr->data                && arr[i] > temp.min)) {            // Create NodeDetails for newNode            // and add it to the queue            newNode.ptr = getNode(arr[i++]);            newNode.min = temp.min;            newNode.max = temp.ptr->data;            q.push(newNode);            // Make this 'newNode' as left child            // of 'temp.ptr'            temp.ptr->left = newNode.ptr;        }        // Check whether there are more elements        // in the arr[] and arr[i] can be        // right child of 'temp.ptr' or not        if(i < n            && (arr[i] > temp.ptr->data                && arr[i] < temp.max)) {            // Create NodeDetails for newNode            // and add it to the queue            newNode.ptr = getNode(arr[i++]);            newNode.min = temp.ptr->data;            newNode.max = temp.max;            q.push(newNode);            // Make this 'newNode' as right            // child of 'temp.ptr'            temp.ptr->right = newNode.ptr;        }    }    // Root of the required BST    returnroot;}// Driver codeintmain(){    intn = 9;    intarr[n] = { 7, 4, 12, 3, 6, 8, 1, 5, 10 };        // Function Call    Node* root = constructBst(arr, n);    preorderTraversal(root);    return0;} | 
Java
| // JAVA program to construct BST// using level order traversalimportjava.io.*;importjava.util.*;// Node class of a binary treeclassNode {    intdata;    Node left, right;    publicNode(intdata)    {        this.data = data;        left = right = null;    }}// Class formed to store the// details of the ancestorsclassNodeDetails {    Node node;    intmin, max;    publicNodeDetails(Node node, intmin, intmax)    {        this.node = node;        this.min = min;        this.max = max;    }}classGFG {    // Function for the preorder traversal    publicstaticvoidpreorder(Node root)    {        if(root == null)            return;        System.out.print(root.data + " ");        // traversing left child        preorder(root.left);        // traversing right child        preorder(root.right);    }        // Function to construct BST    publicstaticNode constructBST(int[] arr, intn)    {        // creating root of the BST        Node root = newNode(arr[0]);        Queue<NodeDetails> q = newLinkedList<>();        // node details for the root of the BST        q.add(newNodeDetails(root, Integer.MIN_VALUE,                              Integer.MAX_VALUE));        // index variable to access array elements        inti = 1;        // until queue is not empty        while(!q.isEmpty()) {            // extracting NodeDetails of a node from the            // queue            NodeDetails temp = q.poll();            Node c = temp.node;            intmin = temp.min, max = temp.max;            // checking whether there are more elements in            // the array and arr[i] can be left child of            // 'temp.node' or not            if(i < n && min < arr[i] && arr[i] < c.data) {                // make this node as left child of                // 'temp.node'                c.left = newNode(arr[i]);                i++;                // create new node details and add it to                // queue                q.add(newNodeDetails(c.left, min, c.data));            }            // checking whether there are more elements in            // the array and arr[i] can be right child of            // 'temp.node' or not            if(i < n && c.data < arr[i] && arr[i] < max) {                // make this node as right child of                // 'temp.node'                c.right = newNode(arr[i]);                i++;                // create new node details and add it to                // queue                q.add(                    newNodeDetails(c.right, c.data, max));            }        }        // root of the required BST        returnroot;    }    // Driver code    publicstaticvoidmain(String[] args)    {        intn = 9;        int[] arr = { 7, 4, 12, 3, 6, 8, 1, 5, 10};        // Function Call        Node root = constructBST(arr, n);        preorder(root);    }} | 
Python3
| # Python program to construct BST# using level order traversal# Node class of a binary treeclassNode:    def__init__(self,data):            self.data =data        self.left =None        self.right =None    # Class formed to store the# details of the ancestorsclassNodeDetails:    def__init__(self,node, min, Max):            self.node =node        self.min=min        self.max=Max    # Function for the preorder traversaldefpreorder(root):    if(root ==None):        return            print(root.data ,end =" ")    # Traversing left child    preorder(root.left)    # Traversing right child    preorder(root.right)# Function to construct BSTdefconstructBST(arr, n):        # Creating root of the BST    root =Node(arr[0])    q =[]    # Node details for the root of the BST    q.append(NodeDetails(root, -1000000000,                                  1000000000))    # Index variable to access array elements    i =1    # Until queue is not empty    while(len(q) !=0):                # Extracting NodeDetails of a node        # from the queue        temp =q[0]        q =q[1:]        c =temp.node        Min=temp.min        Max=temp.max        # Checking whether there are more         # elements in the array and arr[i]         # can be left child of        # 'temp.node' or not        if(i < n andMin< arr[i] andarr[i] < c.data):                         # Make this node as left child of            # 'temp.node'            c.left =Node(arr[i])            i +=1            # Create new node details and add             # it to queue            q.append(NodeDetails(c.left, Min,                                       c.data))        # Checking whether there are more elements in        # the array and arr[i] can be right child of        # 'temp.node' or not        if(i < n andc.data < arr[i] andarr[i] < Max):                        # Make this node as right child of            # 'temp.node'            c.right =Node(arr[i])            i +=1            # Create new node details and add it to            # queue            q.append(NodeDetails(c.right,                                     c.data, Max))        # Root of the required BST    returnroot# Driver coden =9arr =[ 7, 4, 12, 3, 6, 8, 1, 5, 10]# Function Callroot =constructBST(arr, n)preorder(root)# This code is contributed by shinjanpatra | 
C#
| // C# program to construct BST// using level order traversalusingSystem;usingSystem.Collections.Generic;// Node class of a binary treepublicclassNode{    publicintdata;    publicNode left, right;    publicNode(intdata)    {        this.data = data;        left = right = null;    }}// Class formed to store the// details of the ancestorspublicclassNodeDetails{    publicNode node;    publicintmin, max;        publicNodeDetails(Node node, intmin,                                   intmax)    {        this.node = node;        this.min = min;        this.max = max;    }}classGFG{// Function for the preorder traversalpublicstaticvoidpreorder(Node root){    if(root == null)        return;            Console.Write(root.data + " ");    // Traversing left child    preorder(root.left);    // Traversing right child    preorder(root.right);}// Function to construct BSTpublicstaticNode constructBST(int[] arr, intn){        // Creating root of the BST    Node root = newNode(arr[0]);    Queue<NodeDetails> q = newQueue<NodeDetails>();    // Node details for the root of the BST    q.Enqueue(newNodeDetails(root, int.MinValue,                                    int.MaxValue));    // Index variable to access array elements    inti = 1;    // Until queue is not empty    while(q.Count != 0)    {                // Extracting NodeDetails of a node        // from the queue        NodeDetails temp = q.Dequeue();        Node c = temp.node;        intmin = temp.min, max = temp.max;        // Checking whether there are more         // elements in the array and arr[i]         // can be left child of        // 'temp.node' or not        if(i < n && min < arr[i] &&                  arr[i] < c.data)         {                        // Make this node as left child of            // 'temp.node'            c.left = newNode(arr[i]);            i++;            // Create new node details and add             // it to queue            q.Enqueue(newNodeDetails(c.left, min,                                       c.data));        }        // Checking whether there are more elements in        // the array and arr[i] can be right child of        // 'temp.node' or not        if(i < n && c.data < arr[i] && arr[i] < max)        {                        // Make this node as right child of            // 'temp.node'            c.right = newNode(arr[i]);            i++;            // Create new node details and add it to            // queue            q.Enqueue( newNodeDetails(c.right,                                        c.data, max));        }    }    // Root of the required BST    returnroot;}// Driver codepublicstaticvoidMain(String[] args){    intn = 9;    int[] arr = { 7, 4, 12, 3, 6, 8, 1, 5, 10 };    // Function Call    Node root = constructBST(arr, n);        preorder(root);}}// This code is contributed by Princi Singh | 
Javascript
| <script>// Javascript program to construct BST// using level order traversal// Node class of a binary treeclass Node{    constructor(data)    {        this.data = data;        this.left = null;        this.right = null;    }}// Class formed to store the// details of the ancestorsclass NodeDetails{    constructor(node, min, max)    {        this.node = node;        this.min = min;        this.max = max;    }}// Function for the preorder traversalfunctionpreorder(root){    if(root == null)        return;            document.write(root.data + " ");    // Traversing left child    preorder(root.left);    // Traversing right child    preorder(root.right);}// Function to construct BSTfunctionconstructBST(arr, n){        // Creating root of the BST    varroot = newNode(arr[0])    varq = [];    // Node details for the root of the BST    q.push(newNodeDetails(root, -1000000000,                                  1000000000));    // Index variable to access array elements    vari = 1;    // Until queue is not empty    while(q.length != 0)    {                // Extracting NodeDetails of a node        // from the queue        vartemp = q.shift();        varc = temp.node;        varmin = temp.min, max = temp.max;        // Checking whether there are more         // elements in the array and arr[i]         // can be left child of        // 'temp.node' or not        if(i < n && min < arr[i] &&                  arr[i] < c.data)         {                        // Make this node as left child of            // 'temp.node'            c.left = newNode(arr[i]);            i++;            // Create new node details and add             // it to queue            q.push(newNodeDetails(c.left, min,                                       c.data));        }        // Checking whether there are more elements in        // the array and arr[i] can be right child of        // 'temp.node' or not        if(i < n && c.data < arr[i] && arr[i] < max)        {                        // Make this node as right child of            // 'temp.node'            c.right = newNode(arr[i]);            i++;            // Create new node details and add it to            // queue            q.push( newNodeDetails(c.right,                                     c.data, max));        }    }    // Root of the required BST    returnroot;}// Driver codevarn = 9;vararr = [ 7, 4, 12, 3, 6, 8, 1, 5, 10 ];// Function Callvarroot = constructBST(arr, n);preorder(root);// This code is contributed by noob2000</script> | 
7 4 3 1 6 5 12 8 10
Time Complexity: O(N)
Auxiliary Space: O(N) due to queue data structure
Recursive Approach:
Below is the recursion methods to construct BST.
C++
| // C++ implementation to construct a BST// from its level order traversal#include<bits/stdc++.h>usingnamespacestd;// Node* of a BSTstructNode{    intdata;    Node* left;    Node* right;         Node(intdata)    {        this->data = data;        this->left  = NULL;        this->right = NULL;    }}; Node* root; // Function to print the inorder traversalvoidpreorderTraversal(Node* root) {    if(root == NULL)        return;             cout<<(root->data) << " ";         preorderTraversal(root->left);    preorderTraversal(root->right);} // Function to get a new Node*Node* getNode(intdata){         // Allocate memory    Node* node = newNode(data);     returnnode;} // Function to construct a BST from// its level order traversalNode* LevelOrder(Node* root, intdata){    if(root == NULL)    {        root = getNode(data);        returnroot;    }     if(data <= root->data)        root->left = LevelOrder(root->left, data);    else        root->right = LevelOrder(root->right, data);    returnroot;} Node* constructBst(intarr[], intn){    if(n == 0)        returnNULL;              root = NULL;     for(inti = 0; i < n; i++)        root = LevelOrder(root, arr[i]);     returnroot;} // Driver codeintmain(){    intarr[] = { 7, 4, 12, 3, 6,                   8, 1, 5, 10 };                       intn = sizeof(arr)/sizeof(arr[0]);     // Function Call    root = constructBst(arr, n);    preorderTraversal(root);    return0;}// This code is contributed by pratham76 | 
Java
| // Java implementation to construct a BST// from its level order traversalclassGFG{// Node of a BSTstaticclassNode{    intdata;    Node left;    Node right;        Node(intdata)    {        this.data = data;        this.left  = null;        this.right = null;    }};staticNode root;// Function to print the inorder traversalstaticvoidpreorderTraversal(Node root) {    if(root == null)        return;            System.out.print(root.data + " ");        preorderTraversal(root.left);    preorderTraversal(root.right);}// Function to get a new nodestaticNode getNode(intdata){        // Allocate memory    Node node = newNode(data);    returnnode;}// Function to construct a BST from// its level order traversalstaticNode LevelOrder(Node root, intdata){    if(root == null)    {        root = getNode(data);        returnroot;    }    if(data <= root.data)        root.left = LevelOrder(root.left, data);    else        root.right = LevelOrder(root.right, data);    returnroot;}staticNode constructBst(int[]arr, intn){    if(n == 0)        returnnull;             root = null;    for(inti = 0; i < n; i++)        root = LevelOrder(root, arr[i]);    returnroot;}// Driver codepublicstaticvoidmain(String[] args){    int[] arr = { 7, 4, 12, 3, 6,                   8, 1, 5, 10};                      intn = arr.length;    // Function Call    root = constructBst(arr, n);    preorderTraversal(root);}}// This code is contributed by shikhasingrajput | 
Python3
| # Python3 implementation to construct a BST# from its level order traversalimportmath# node of a BSTclassNode:    def__init__(self, data):        self.data =data        self.left =None        self.right =None# function to print the inorder traversaldefpreorderTraversal(root):    if(root ==None):        returnNone    print(root.data, end=" ")    preorderTraversal(root.left)    preorderTraversal(root.right)# function to get a new nodedefgetNode(data):    # Allocate memory    newNode =Node(data)    # put in the data    newNode.data =data    newNode.left =None    newNode.right =None    returnnewNode# function to construct a BST from# its level order traversaldefLevelOrder(root, data):    if(root ==None):        root =getNode(data)        returnroot    if(data <=root.data):        root.left =LevelOrder(root.left, data)    else:        root.right =LevelOrder(root.right, data)    returnrootdefconstructBst(arr, n):    if(n ==0):        returnNone    root =None    fori inrange(0, n):        root =LevelOrder(root, arr[i])    returnroot# Driver codeif__name__ =='__main__':    arr =[7, 4, 12, 3, 6, 8, 1, 5, 10]    n =len(arr)    # Function Call    root =constructBst(arr, n)    root =preorderTraversal(root)# This code is contributed by Srathore | 
C#
| // C# implementation to construct a BST// from its level order traversalusingSystem;classGFG{// Node of a BSTpublicclassNode{    publicintdata;    publicNode left;    publicNode right;        publicNode(intdata)    {        this.data = data;        this.left  = null;        this.right = null;    }};staticNode root;// Function to print the inorder traversalstaticvoidpreorderTraversal(Node root) {    if(root == null)        return;            Console.Write(root.data + " ");        preorderTraversal(root.left);    preorderTraversal(root.right);}// Function to get a new nodestaticNode getNode(intdata){        // Allocate memory    Node node = newNode(data);    returnnode;}// Function to construct a BST from// its level order traversalstaticNode LevelOrder(Node root, intdata){    if(root == null)    {        root = getNode(data);        returnroot;    }    if(data <= root.data)        root.left = LevelOrder(root.left, data);    else        root.right = LevelOrder(root.right, data);    returnroot;}staticNode constructBst(int[]arr, intn){    if(n == 0)        returnnull;             root = null;    for(inti = 0; i < n; i++)        root = LevelOrder(root, arr[i]);    returnroot;}// Driver codepublicstaticvoidMain(string[] args){    int[] arr = { 7, 4, 12, 3, 6,                   8, 1, 5, 10 };                      intn = arr.Length;    // Function Call    root = constructBst(arr, n);    preorderTraversal(root);}}// This code is contributed by rutvik_56 | 
Javascript
| <script>// JavaScript implementation to construct a BST// from its level order traversal// Node of a BSTclass Node{       constructor(data)    {        this.data = data;        this.left  = null;        this.right = null;    }} let root; // Function to print the inorder traversalfunctionpreorderTraversal(root) {    if(root == null)        return;             document.write(root.data," ");         preorderTraversal(root.left);    preorderTraversal(root.right);} // Function to get a new Node*functiongetNode(data){         // Allocate memory    let node = newNode(data);     returnnode;} // Function to construct a BST from// its level order traversalfunctionLevelOrder(root,data){    if(root == null)    {        root = getNode(data);        returnroot;    }     if(data <= root.data)        root.left = LevelOrder(root.left, data);    else        root.right = LevelOrder(root.right, data);    returnroot;} functionconstructBst(arr, n){    if(n == 0)        returnnull;              root = null;     for(let i = 0; i < n; i++)        root = LevelOrder(root, arr[i]);     returnroot;} // Driver codelet arr = [ 7, 4, 12, 3, 6, 8, 1, 5, 10 ];                   let n = arr.length; // Function Callroot = constructBst(arr, n);preorderTraversal(root);// code is contributed by shinjanpatra</script> | 
7 4 3 1 6 5 12 8 10
Time Complexity for Python Code O(N log(N))
 
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

 
                                    







