Construct BST from its given level order traversal | Set-2
Last Updated :
12 Jul, 2025
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>
using namespace std;
// Node structure of a binary tree
struct Node {
int data;
Node* right;
Node* left;
Node(int x)
{
data = x;
right = NULL;
left = NULL;
}
};
// Structure formed to store the
// details of the ancestor
struct NodeDetails {
Node* ptr;
int min, max;
};
// Function for the preorder traversal
void preorderTraversal(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 pointer
Node* getNode(int data)
{
Node* temp = new Node(0);
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// Function to construct the BST
Node* constructBst(int arr[], int n)
{
if (n == 0)
return NULL;
Node* root;
queue<NodeDetails> q;
// index variable to
// access array elements
int i = 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
return root;
}
// Driver code
int main()
{
int n = 9;
int arr[n] = { 7, 4, 12, 3, 6, 8, 1, 5, 10 };
// Function Call
Node* root = constructBst(arr, n);
preorderTraversal(root);
return 0;
}
Java
// JAVA program to construct BST
// using level order traversal
import java.io.*;
import java.util.*;
// Node class of a binary tree
class Node {
int data;
Node left, right;
public Node(int data)
{
this.data = data;
left = right = null;
}
}
// Class formed to store the
// details of the ancestors
class NodeDetails {
Node node;
int min, max;
public NodeDetails(Node node, int min, int max)
{
this.node = node;
this.min = min;
this.max = max;
}
}
class GFG {
// Function for the preorder traversal
public static void preorder(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
public static Node constructBST(int[] arr, int n)
{
// creating root of the BST
Node root = new Node(arr[0]);
Queue<NodeDetails> q = new LinkedList<>();
// node details for the root of the BST
q.add(new NodeDetails(root, Integer.MIN_VALUE,
Integer.MAX_VALUE));
// index variable to access array elements
int i = 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;
int 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 && min < arr[i] && arr[i] < c.data) {
// make this node as left child of
// 'temp.node'
c.left = new Node(arr[i]);
i++;
// create new node details and add it to
// queue
q.add(new 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 && c.data < arr[i] && arr[i] < max) {
// make this node as right child of
// 'temp.node'
c.right = new Node(arr[i]);
i++;
// create new node details and add it to
// queue
q.add(
new NodeDetails(c.right, c.data, max));
}
}
// root of the required BST
return root;
}
// Driver code
public static void main(String[] args)
{
int n = 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 tree
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
# Class formed to store the
# details of the ancestors
class NodeDetails:
def __init__(self ,node, min, Max):
self.node = node
self.min = min
self.max = Max
# Function for the preorder traversal
def preorder(root):
if (root == None):
return
print(root.data ,end = " ")
# Traversing left child
preorder(root.left)
# Traversing right child
preorder(root.right)
# Function to construct BST
def constructBST(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 and Min < arr[i] and arr[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 and c.data < arr[i] and arr[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
return root
# Driver code
n = 9
arr = [ 7, 4, 12, 3, 6, 8, 1, 5, 10 ]
# Function Call
root = constructBST(arr, n)
preorder(root)
# This code is contributed by shinjanpatra
C#
// C# program to construct BST
// using level order traversal
using System;
using System.Collections.Generic;
// Node class of a binary tree
public class Node
{
public int data;
public Node left, right;
public Node(int data)
{
this.data = data;
left = right = null;
}
}
// Class formed to store the
// details of the ancestors
public class NodeDetails
{
public Node node;
public int min, max;
public NodeDetails(Node node, int min,
int max)
{
this.node = node;
this.min = min;
this.max = max;
}
}
class GFG{
// Function for the preorder traversal
public static void preorder(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 BST
public static Node constructBST(int[] arr, int n)
{
// Creating root of the BST
Node root = new Node(arr[0]);
Queue<NodeDetails> q = new Queue<NodeDetails>();
// Node details for the root of the BST
q.Enqueue(new NodeDetails(root, int.MinValue,
int.MaxValue));
// Index variable to access array elements
int i = 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;
int 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 && min < arr[i] &&
arr[i] < c.data)
{
// Make this node as left child of
// 'temp.node'
c.left = new Node(arr[i]);
i++;
// Create new node details and add
// it to queue
q.Enqueue(new 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 && c.data < arr[i] && arr[i] < max)
{
// Make this node as right child of
// 'temp.node'
c.right = new Node(arr[i]);
i++;
// Create new node details and add it to
// queue
q.Enqueue( new NodeDetails(c.right,
c.data, max));
}
}
// Root of the required BST
return root;
}
// Driver code
public static void Main(String[] args)
{
int n = 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 tree
class Node
{
constructor(data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
// Class formed to store the
// details of the ancestors
class NodeDetails
{
constructor(node, min, max)
{
this.node = node;
this.min = min;
this.max = max;
}
}
// Function for the preorder traversal
function preorder(root)
{
if (root == null)
return;
document.write(root.data + " ");
// Traversing left child
preorder(root.left);
// Traversing right child
preorder(root.right);
}
// Function to construct BST
function constructBST(arr, n)
{
// Creating root of the BST
var root = new Node(arr[0])
var q = [];
// Node details for the root of the BST
q.push(new NodeDetails(root, -1000000000,
1000000000));
// Index variable to access array elements
var i = 1;
// Until queue is not empty
while (q.length != 0)
{
// Extracting NodeDetails of a node
// from the queue
var temp = q.shift();
var c = temp.node;
var 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 && min < arr[i] &&
arr[i] < c.data)
{
// Make this node as left child of
// 'temp.node'
c.left = new Node(arr[i]);
i++;
// Create new node details and add
// it to queue
q.push(new 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 && c.data < arr[i] && arr[i] < max)
{
// Make this node as right child of
// 'temp.node'
c.right = new Node(arr[i]);
i++;
// Create new node details and add it to
// queue
q.push( new NodeDetails(c.right,
c.data, max));
}
}
// Root of the required BST
return root;
}
// Driver code
var n = 9;
var arr = [ 7, 4, 12, 3, 6, 8, 1, 5, 10 ];
// Function Call
var root = constructBST(arr, n);
preorder(root);
// This code is contributed by noob2000
</script>
Output: 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>
using namespace std;
// Node* of a BST
struct Node
{
int data;
Node* left;
Node* right;
Node(int data)
{
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
Node* root;
// Function to print the inorder traversal
void preorderTraversal(Node* root)
{
if (root == NULL)
return;
cout<<(root->data) << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// Function to get a new Node*
Node* getNode(int data)
{
// Allocate memory
Node* node = new Node(data);
return node;
}
// Function to construct a BST from
// its level order traversal
Node* LevelOrder(Node* root, int data)
{
if (root == NULL)
{
root = getNode(data);
return root;
}
if (data <= root->data)
root->left = LevelOrder(root->left, data);
else
root->right = LevelOrder(root->right, data);
return root;
}
Node* constructBst(int arr[], int n)
{
if (n == 0)
return NULL;
root = NULL;
for(int i = 0; i < n; i++)
root = LevelOrder(root, arr[i]);
return root;
}
// Driver code
int main()
{
int arr[] = { 7, 4, 12, 3, 6,
8, 1, 5, 10 };
int n = sizeof(arr)/sizeof(arr[0]);
// Function Call
root = constructBst(arr, n);
preorderTraversal(root);
return 0;
}
// This code is contributed by pratham76
Java
// Java implementation to construct a BST
// from its level order traversal
class GFG{
// Node of a BST
static class Node
{
int data;
Node left;
Node right;
Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
};
static Node root;
// Function to print the inorder traversal
static void preorderTraversal(Node root)
{
if (root == null)
return;
System.out.print(root.data + " ");
preorderTraversal(root.left);
preorderTraversal(root.right);
}
// Function to get a new node
static Node getNode(int data)
{
// Allocate memory
Node node = new Node(data);
return node;
}
// Function to construct a BST from
// its level order traversal
static Node LevelOrder(Node root, int data)
{
if (root == null)
{
root = getNode(data);
return root;
}
if (data <= root.data)
root.left = LevelOrder(root.left, data);
else
root.right = LevelOrder(root.right, data);
return root;
}
static Node constructBst(int []arr, int n)
{
if (n == 0)
return null;
root = null;
for(int i = 0; i < n; i++)
root = LevelOrder(root, arr[i]);
return root;
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 7, 4, 12, 3, 6,
8, 1, 5, 10 };
int n = 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 traversal
import math
# node of a BST
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# function to print the inorder traversal
def preorderTraversal(root):
if (root == None):
return None
print(root.data, end=" ")
preorderTraversal(root.left)
preorderTraversal(root.right)
# function to get a new node
def getNode(data):
# Allocate memory
newNode = Node(data)
# put in the data
newNode.data = data
newNode.left = None
newNode.right = None
return newNode
# function to construct a BST from
# its level order traversal
def LevelOrder(root, data):
if(root == None):
root = getNode(data)
return root
if(data <= root.data):
root.left = LevelOrder(root.left, data)
else:
root.right = LevelOrder(root.right, data)
return root
def constructBst(arr, n):
if(n == 0):
return None
root = None
for i in range(0, n):
root = LevelOrder(root, arr[i])
return root
# Driver code
if __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 traversal
using System;
class GFG{
// Node of a BST
public class Node
{
public int data;
public Node left;
public Node right;
public Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
};
static Node root;
// Function to print the inorder traversal
static void preorderTraversal(Node root)
{
if (root == null)
return;
Console.Write(root.data + " ");
preorderTraversal(root.left);
preorderTraversal(root.right);
}
// Function to get a new node
static Node getNode(int data)
{
// Allocate memory
Node node = new Node(data);
return node;
}
// Function to construct a BST from
// its level order traversal
static Node LevelOrder(Node root, int data)
{
if (root == null)
{
root = getNode(data);
return root;
}
if (data <= root.data)
root.left = LevelOrder(root.left, data);
else
root.right = LevelOrder(root.right, data);
return root;
}
static Node constructBst(int []arr, int n)
{
if (n == 0)
return null;
root = null;
for(int i = 0; i < n; i++)
root = LevelOrder(root, arr[i]);
return root;
}
// Driver code
public static void Main(string[] args)
{
int[] arr = { 7, 4, 12, 3, 6,
8, 1, 5, 10 };
int n = 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 BST
class Node
{
constructor(data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
let root;
// Function to print the inorder traversal
function preorderTraversal(root)
{
if (root == null)
return;
document.write(root.data," ");
preorderTraversal(root.left);
preorderTraversal(root.right);
}
// Function to get a new Node*
function getNode(data)
{
// Allocate memory
let node = new Node(data);
return node;
}
// Function to construct a BST from
// its level order traversal
function LevelOrder(root,data)
{
if (root == null)
{
root = getNode(data);
return root;
}
if (data <= root.data)
root.left = LevelOrder(root.left, data);
else
root.right = LevelOrder(root.right, data);
return root;
}
function constructBst(arr, n)
{
if (n == 0)
return null;
root = null;
for(let i = 0; i < n; i++)
root = LevelOrder(root, arr[i]);
return root;
}
// Driver code
let arr = [ 7, 4, 12, 3, 6, 8, 1, 5, 10 ];
let n = arr.length;
// Function Call
root = constructBst(arr, n);
preorderTraversal(root);
// code is contributed by shinjanpatra
</script>
Output: 7 4 3 1 6 5 12 8 10
Time Complexity for Python Code O(N log(N))
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem