Construct BST from its given level order traversal
Last Updated :
01 Dec, 2023
Construct the BST (Binary Search Tree) from its given level order traversal.
Examples:
Input: arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10}
Output: BST:
7
/ \
4 12
/ \ /
3 6 8
/ / \
1 5 10
Construct BST from its given level order traversal Using Recursion:
The idea is to use recursion as the first element will always be the root of the tree and second element will be the left child and the third element will be the right child (if fall in the range), and so on for all the remaining elements.
Follow the steps below to solve the problem:
- First, pick the first element of the array and make it root.
- Pick the second element, if its value is smaller than the root node value make it left child,
- Else make it right child
- Now recursively call step (2) and step (3) to make a BST from its level Order Traversal.
Below is the implementation of the above approach:
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, *right;
};
// function to get a new node
Node* getNode(int data)
{
// Allocate memory
Node* newNode = (Node*)malloc(sizeof(Node));
// put in the data
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// 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;
Node* root = NULL;
for (int i = 0; i < n; i++)
root = LevelOrder(root, arr[i]);
return root;
}
// function to print the inorder traversal
void inorderTraversal(Node* root)
{
if (!root)
return;
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}
// 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]);
Node* root = constructBst(arr, n);
cout << "Inorder Traversal: ";
inorderTraversal(root);
return 0;
}
Java
// Java implementation to construct a BST
// from its level order traversal
import java.io.*;
class GFG {
// node of a BST
static class Node {
int data;
Node left, right;
};
// function to get a new node
static Node getNode(int data)
{
// Allocate memory
Node newNode = new Node();
// put in the data
newNode.data = data;
newNode.left = newNode.right = null;
return newNode;
}
// 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;
Node root = null;
for (int i = 0; i < n; i++)
root = LevelOrder(root, arr[i]);
return root;
}
// function to print the inorder traversal
static void inorderTraversal(Node root)
{
if (root == null)
return;
inorderTraversal(root.left);
System.out.print(root.data + " ");
inorderTraversal(root.right);
}
// Driver code
public static void main(String args[])
{
int arr[] = { 7, 4, 12, 3, 6, 8, 1, 5, 10 };
int n = arr.length;
Node root = constructBst(arr, n);
System.out.print("Inorder Traversal: ");
inorderTraversal(root);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python 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 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
# Function to print the inorder traversal
def inorderTraversal(root):
if (root == None):
return None
inorderTraversal(root.left)
print(root.data, end=" ")
inorderTraversal(root.right)
# Driver program
if __name__ == '__main__':
arr = [7, 4, 12, 3, 6, 8, 1, 5, 10]
n = len(arr)
root = constructBst(arr, n)
print("Inorder Traversal: ", end="")
root = inorderTraversal(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, right;
};
// function to get a new node
static Node getNode(int data)
{
// Allocate memory
Node newNode = new Node();
// put in the data
newNode.data = data;
newNode.left = newNode.right = null;
return newNode;
}
// 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;
Node root = null;
for (int i = 0; i < n; i++)
root = LevelOrder(root, arr[i]);
return root;
}
// function to print the inorder traversal
static void inorderTraversal(Node root)
{
if (root == null)
return;
inorderTraversal(root.left);
Console.Write(root.data + " ");
inorderTraversal(root.right);
}
// Driver code
public static void Main(String[] args)
{
int[] arr = { 7, 4, 12, 3, 6, 8, 1, 5, 10 };
int n = arr.Length;
Node root = constructBst(arr, n);
Console.Write("Inorder Traversal: ");
inorderTraversal(root);
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// JavaScript implementation to construct a BST
// from its level order traversal
// node of a BST
class Node {
constructor() {
this.data = 0;
this.left = null;
this.right = null;
}
}
// function to get a new node
function getNode(data) {
// Allocate memory
var newNode = new Node();
// put in the data
newNode.data = data;
newNode.left = newNode.right = null;
return newNode;
}
// 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;
var root = null;
for (var i = 0; i < n; i++)
root = LevelOrder(root, arr[i]);
return root;
}
// function to print the inorder traversal
function inorderTraversal(root) {
if (root == null) return;
inorderTraversal(root.left);
document.write(root.data + " ");
inorderTraversal(root.right);
}
// Driver code
var arr = [7, 4, 12, 3, 6, 8, 1, 5, 10];
var n = arr.length;
var root = constructBst(arr, n);
document.write("Inorder Traversal: ");
inorderTraversal(root);
</script>
OutputInorder Traversal: 1 3 4 5 6 7 8 10 12
Time Complexity: O(N * H), Where N is the number of nodes in the tree and H is the height of the tree
Auxiliary Space: O(N), N is the number of nodes in the Tree
Construct BST from its given level order traversal Using Queue:
The idea is similar to what we do while finding the level order traversal of a binary tree using the queue. In this case, we maintain a queue that contains a pair of the Node class and an integer pair storing the range for each of the tree nodes.
Follow the below steps to Implement the above idea:
- Create an empty queue q<pair<Node*,pair<int,int>>> and push root and range from - infinite to + infinite in q.
- Run for loop through the entire array containing the level order traversal
- Get the front of the queue and store its Node (in temp variable) and its range.
- If arr[i] can be a child of temp by checking the value is within the range.
- Check whether arr[i] can be a left child or right child of the Node by checking the condition of BST.
- If arr[i] can be a left child, we create a new Node and point it to the left child of temp.
- We update the range such that its new lower bound is the same as before and it's new upper bound is the value of temp node.
- If arr[i] can be the right child, we create a new Node and point it to the right child of temp.
- We update the range such that it's new lower bound is the value of temp node and its new upper bound is the same as before.
- Pop the temp node from the queue once the right child is set. This is because the temp node cannot have any more children.
- Else we pop out the node from the queue, decrement i and go ahead.
- Initialize temp_node = q.front() and print temp_node->data.
- Push temp_node’s children i.e. temp_node -> left then temp_node -> right to q
- Pop front node from q.
- Finally, return the head of the tree.
Below is the Implementation of the above approach:
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, *right;
Node(int x)
{
data = x;
right = NULL;
left = NULL;
}
};
// Function to construct a BST from
// its level order traversal
Node* constructBst(int arr[], int n)
{
// Create queue to store the tree nodes
queue<pair<Node*, pair<int, int> > > q;
// If array is empty we return NULL
if (n == 0)
return NULL;
// Create root node and store a copy of it in head
Node *root = new Node(arr[0]), *head = root;
// Push the root node and the initial range
q.push({ root, { INT_MIN, INT_MAX } });
// Loop over the contents of arr to process all the
// elements
for (int i = 1; i < n; i++) {
// Get the node and the range at the front of the
// queue
Node* temp = q.front().first;
pair<int, int> range = q.front().second;
// Check if arr[i] can be a child of the temp node
if (arr[i] > range.first && arr[i] < range.second) {
// Check if arr[i] can be left child
if (arr[i] < temp->data) {
if(temp->left != NULL){
//if temp already has a left child
//temp can have no more children
q.pop();
i--;
continue;
}
// Set the left child and range
temp->left = new Node(arr[i]);
q.push({ temp->left,
{ range.first, temp->data } });
}
// Check if arr[i] can be left child
else {
// Pop the temp node from queue, set the
// right child and new range
q.pop();
temp->right = new Node(arr[i]);
q.push({ temp->right,
{ temp->data, range.second } });
}
}
else {
q.pop();
i--;
}
}
return head;
}
// Function to print the inorder traversal
void inorderTraversal(Node* root)
{
if (!root)
return;
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}
// 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]);
Node* root = constructBst(arr, n);
cout << "Inorder Traversal: ";
inorderTraversal(root);
return 0;
}
// This code is contributed by Rohit Iyer (rohit_iyer)
Java
// Java code for the above approach
import java.io.*;
import java.util.*;
// Node of a BST
class Node {
int data;
Node left, right;
public Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
public class GFG {
static class NodeRange {
Node node;
int min, max;
public NodeRange(Node node, int min, int max)
{
this.node = node;
this.min = min;
this.max = max;
}
}
public static Node constructBst(int[] arr)
{
if (arr.length == 0)
return null;
// Create root node and store a copy of it in head
Node root = new Node(arr[0]), head = root;
// Create queue to store the tree nodes
Queue<NodeRange> queue = new LinkedList<>();
queue.add(new NodeRange(root, Integer.MIN_VALUE,
Integer.MAX_VALUE));
for (int i = 1; i < arr.length; i++) {
NodeRange nr = queue.peek();
// Check if arr[i] can be a child of the temp
// node
if (arr[i] > nr.min && arr[i] < nr.max) {
// Check if arr[i] can be left child
if (arr[i] < nr.node.data) {
// Set the left child and range
nr.node.left = new Node(arr[i]);
queue.add(new NodeRange(nr.node.left,
nr.min,
nr.node.data));
}
// Check if arr[i] can be right child
else {
// Pop the temp node from queue, set the
// right child and new range
queue.remove();
nr.node.right = new Node(arr[i]);
queue.add(new NodeRange(nr.node.right,
nr.node.data,
nr.max));
}
}
else {
queue.remove();
i--;
}
}
return head;
}
public static void inorderTraversal(Node root)
{
if (root == null)
return;
inorderTraversal(root.left);
System.out.print(root.data + " ");
inorderTraversal(root.right);
}
public static void main(String[] args)
{
int[] arr = { 7, 4, 12, 3, 6, 8, 1, 5, 10 };
Node root = constructBst(arr);
System.out.print("Inorder Traversal: ");
inorderTraversal(root);
}
}
// This code is contributed by sankar.
Python3
# Python implementation to construct a BST
# from its level order traversal
# Importing essential libraries
from collections import deque
# Node of a BST
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def constructBst(arr, n):
queue = deque()
if n == 0:
return None
# Create root node and store a copy of it in head
root = Node(arr[0])
head = root
# Push the root node and the initial range
queue.append((root, (-float("inf"), float("inf"))))
i = 1
# Loop over the contents of arr to process all the elements using
# while loop we may have to process atmost 2 child's
while i < n:
# Get the node and the range at the front of the queue
# and popout the leftmost element
temp = queue[0][0]
tempRange = queue[0][1]
queue.popleft()
# Check if arr[i] can be left child and within range of it's parent data
if (arr[i] < temp.data) and tempRange[0] < arr[i] < tempRange[1]:
# Set the left child and new range for the child
temp.left = Node(arr[i])
queue.append((temp.left, (tempRange[0], temp.data)))
i += 1
# Check if arr[i] can be right child and within range of it's parent data
if arr[i] > temp.data and tempRange[0] < arr[i] < tempRange[1]:
# Set the right child and new range for the child
temp.right = Node(arr[i])
queue.append((temp.right, (temp.data, tempRange[1])))
i += 1
return head
def inorderTraversal(root):
if (root == None):
return None
inorderTraversal(root.left)
print(root.data, end=" ")
inorderTraversal(root.right)
# Driver program
if __name__ == '__main__':
arr = [7, 4, 12, 3, 6, 8, 1, 5, 10]
n = len(arr)
root = constructBst(arr, n)
print("Inorder Traversal: ")
root = inorderTraversal(root)
# This code is contributed by Divyanshu Singh
C#
using System;
using System.Collections.Generic;
// Node of a BST
class Node {
public int data;
public Node left;
public Node right;
public Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
class BST {
public Node constructBst(int[] arr, int n)
{
var queue
= new Queue<Tuple<Node, Tuple<int, int> > >();
if (n == 0)
return null;
// Create root node and store a copy of it in head
var root = new Node(arr[0]);
var head = root;
// Push the root node and the initial range
queue.Enqueue(
Tuple.Create(root, Tuple.Create(int.MinValue,
int.MaxValue)));
int i = 1;
// Loop over the contents of arr to process all the
// elements using while loop we may have to process
// atmost 2 child's
while (i < n) {
// Get the node and the range at the front of
// the queue and popout the leftmost element
var temp = queue.Dequeue();
var tempRange = temp.Item2;
// Check if arr[i] can be left child and within
// range of it's parent data
if (arr[i] < temp.Item1.data
&& tempRange.Item1 < arr[i]
&& arr[i] < tempRange.Item2) {
// Set the left child and new range for the
// child
temp.Item1.left = new Node(arr[i]);
queue.Enqueue(Tuple.Create(
temp.Item1.left,
Tuple.Create(tempRange.Item1,
temp.Item1.data)));
i++;
}
// Check if arr[i] can be right child and within
// range of it's parent data
if (arr[i] > temp.Item1.data
&& tempRange.Item1 < arr[i]
&& arr[i] < tempRange.Item2) {
// Set the right child and new range for the
// child
temp.Item1.right = new Node(arr[i]);
queue.Enqueue(Tuple.Create(
temp.Item1.right,
Tuple.Create(temp.Item1.data,
tempRange.Item2)));
i++;
}
}
return head;
}
public void inorderTraversal(Node root)
{
if (root == null)
return;
inorderTraversal(root.left);
Console.Write(root.data + " ");
inorderTraversal(root.right);
}
// Driver program
public static void Main(string[] args)
{
var arr = new int[] { 7, 4, 12, 3, 6, 8, 1, 5, 10 };
int n = arr.Length;
var bst = new BST();
var root = bst.constructBst(arr, n);
Console.WriteLine("Inorder Traversal:");
bst.inorderTraversal(root);
}
}
JavaScript
// Javascript code for the above approach
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
function constructBst(arr) {
if (arr.length === 0) return null;
// Create root node and store a copy of it in head
let root = new Node(arr[0]), head = root;
// Create queue to store the tree nodes
let queue = [{ node: root, range: { min: Number.MIN_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER } }];
for (let i = 1; i < arr.length; i++) {
let { node, range } = queue[0];
// Check if arr[i] can be a child of the temp node
if (arr[i] > range.min && arr[i] < range.max) {
// Check if arr[i] can be left child
if (arr[i] < node.data) {
// Set the left child and range
node.left = new Node(arr[i]);
queue.push({ node: node.left, range: { min: range.min, max: node.data } });
}
// Check if arr[i] can be left child
else {
// Pop the temp node from queue, set the right child and new range
queue.shift();
node.right = new Node(arr[i]);
queue.push({ node: node.right, range: { min: node.data, max: range.max } });
}
}
else {
queue.shift();
i--;
}
}
return head;
}
function inorderTraversal(root) {
if (!root) return;
inorderTraversal(root.left);
console.log(root.data+" ");
inorderTraversal(root.right);
}
let arr = [7, 4, 12, 3, 6, 8, 1, 5, 10];
let root = constructBst(arr);
console.log("Inorder Traversal: ");
inorderTraversal(root);
// This code is contributed by lokeshpotta20.
OutputInorder Traversal: 1 3 4 5 6 7 8 10 12
Time Complexity: O(N), Visiting every node once.
Auxiliary Space: O(N), Using queue to store the nodes
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