[Naive Approach] Using Recursion - O(n * h) space and O(n) space
The idea is to create an empty BST and insert each element from the level order array one by one using the BST insertion property, where smaller elements go to the left subtree and larger elements go to the right subtree.
Steps to solve the problem:
Start with an empty root node.
For each value in the level order array, insert it into the BST using the following rules:
If the current node is null, create a new node with the given value and return it.
If the value is smaller than the current node’s value, recursively insert it into the left subtree.
If the value is larger than the current node’s value, recursively insert it into the right subtree
C++
// C++ program to Construct BST from // its given level order traversal#include<iostream>#include<vector>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};Node*insertIntoBST(Node*root,intval){// If node is null, then we can insert // val here.if(!root)returnnewNode(val);// If value is less than root value, // insert into left subtree.if(val<root->data){root->left=insertIntoBST(root->left,val);}// Else, insert into right subtree.else{root->right=insertIntoBST(root->right,val);}returnroot;}Node*constructBst(vector<int>&arr){intn=arr.size();Node*root=nullptr;// Insert each value one by one for(inti=0;i<n;i++){root=insertIntoBST(root,arr[i]);}returnroot;}voidpreOrder(Node*root){if(!root)return;cout<<root->data<<" ";preOrder(root->left);preOrder(root->right);}intmain(){vector<int>arr={7,4,12,3,6,8,1,5,10};Node*root=constructBst(arr);preOrder(root);return0;}
Java
// Java program to Construct BST from // its given level order traversalclassNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=null;right=null;}}classGfG{// If node is null, then we can insert // val here.staticNodeinsertIntoBST(Noderoot,intval){if(root==null)returnnewNode(val);// If value is less than root value, // insert into left subtree.if(val<root.data){root.left=insertIntoBST(root.left,val);}// Else, insert into right subtree.else{root.right=insertIntoBST(root.right,val);}returnroot;}staticNodeconstructBst(int[]arr){intn=arr.length;Noderoot=null;// Insert each value one by one for(inti=0;i<n;i++){root=insertIntoBST(root,arr[i]);}returnroot;}staticvoidpreOrder(Noderoot){if(root==null)return;System.out.print(root.data+" ");preOrder(root.left);preOrder(root.right);}publicstaticvoidmain(String[]args){int[]arr={7,4,12,3,6,8,1,5,10};Noderoot=constructBst(arr);preOrder(root);}}
Python
# Python program to Construct BST from # its given level order traversalclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# If node is null, then we can insert # val here.definsertIntoBST(root,val):ifnotroot:returnNode(val)# If value is less than root value, # insert into left subtree.ifval<root.data:root.left=insertIntoBST(root.left,val)# Else, insert into right subtree.else:root.right=insertIntoBST(root.right,val)returnrootdefconstructBst(arr):n=len(arr)root=None# Insert each value one by one foriinrange(n):root=insertIntoBST(root,arr[i])returnrootdefpreOrder(root):ifnotroot:returnprint(root.data,end=" ")preOrder(root.left)preOrder(root.right)if__name__=="__main__":arr=[7,4,12,3,6,8,1,5,10]root=constructBst(arr)preOrder(root)
C#
// C# program to Construct BST from // its given level order traversalusingSystem;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}classGfG{// If node is null, then we can insert // val here.staticNodeinsertIntoBST(Noderoot,intval){if(root==null)returnnewNode(val);// If value is less than root value, // insert into left subtree.if(val<root.data){root.left=insertIntoBST(root.left,val);}// Else, insert into right subtree.else{root.right=insertIntoBST(root.right,val);}returnroot;}staticNodeconstructBst(int[]arr){intn=arr.Length;Noderoot=null;// Insert each value one by one for(inti=0;i<n;i++){root=insertIntoBST(root,arr[i]);}returnroot;}staticvoidpreOrder(Noderoot){if(root==null)return;Console.Write(root.data+" ");preOrder(root.left);preOrder(root.right);}staticvoidMain(string[]args){int[]arr={7,4,12,3,6,8,1,5,10};Noderoot=constructBst(arr);preOrder(root);}}
JavaScript
// JavaScript program to Construct BST from // its given level order traversalclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// If node is null, then we can insert // val here.functioninsertIntoBST(root,val){if(root===null)returnnewNode(val);// If value is less than root value, // insert into left subtree.if(val<root.data){root.left=insertIntoBST(root.left,val);}// Else, insert into right subtree.else{root.right=insertIntoBST(root.right,val);}returnroot;}functionconstructBst(arr){letn=arr.length;letroot=null;// Insert each value one by one for(leti=0;i<n;i++){root=insertIntoBST(root,arr[i]);}returnroot;}functionpreOrder(root){if(root===null)return;process.stdout.write(root.data+" ");preOrder(root.left);preOrder(root.right);}// Driver Codeletarr=[7,4,12,3,6,8,1,5,10];letroot=constructBst(arr);preOrder(root);
Output
7 4 3 1 6 5 12 8 10
[Expected Approach] Using Level Order Traversal - O(n) time and O(n) space
The idea is to build the BST level by level using a queue, where each node carries a valid value range. New elements are inserted as left or right children only if they fall within the range, ensuring the BST property is maintained.
Steps to solve the problem:
Take the first element as root and push it into a queue with the value range (−∞, +∞).
For each next element in the level order array, look at the front node and check whether it can be placed in its left or right subtree based on the valid range.
If it fits on the left, create the left child, assign range (low, node->data − 1), and push it to the queue.
If it fits on the right, create the right child, assign range (node->data + 1, high), and push it to the queue.
Continue this process until all elements are inserted and the BST is fully constructed.
C++
// C++ program to Construct BST from // its given level order traversal#include<iostream>#include<vector>#include<queue>#include<climits>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};Node*constructBst(vector<int>&arr){intn=arr.size();Node*root=newNode(arr[0]);queue<pair<Node*,pair<int,int>>>q;q.push({root,{INT_MIN,INT_MAX}});inti=1;while(i<n&&!q.empty()){autocurr=q.front();q.pop();Node*node=curr.first;intlow=curr.second.first;inthigh=curr.second.second;// Check for left childif(i<n&&arr[i]>=low&&arr[i]<node->data){node->left=newNode(arr[i]);q.push({node->left,{low,node->data-1}});i++;}// Check for right childif(i<n&&arr[i]>node->data&&arr[i]<=high){node->right=newNode(arr[i]);q.push({node->right,{node->data+1,high}});i++;}}returnroot;}voidpreOrder(Node*root){if(!root)return;cout<<root->data<<" ";preOrder(root->left);preOrder(root->right);}intmain(){vector<int>arr={7,4,12,3,6,8,1,5,10};Node*root=constructBst(arr);preOrder(root);return0;}
Java
// Java program to Construct BST from // its given level order traversalimportjava.util.*;classNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=null;right=null;}}classPair<X,Y>{publicfinalXfirst;publicfinalYsecond;publicPair(Xfirst,Ysecond){this.first=first;this.second=second;}}classGFG{staticNodeconstructBst(int[]arr){intn=arr.length;Noderoot=newNode(arr[0]);Queue<Pair<Node,Pair<Integer,Integer>>>q=newLinkedList<>();q.add(newPair<>(root,newPair<>(Integer.MIN_VALUE,Integer.MAX_VALUE)));inti=1;while(i<n&&!q.isEmpty()){Pair<Node,Pair<Integer,Integer>>curr=q.poll();Nodenode=curr.first;intlow=curr.second.first;inthigh=curr.second.second;// Check for left childif(i<n&&arr[i]>=low&&arr[i]<node.data){node.left=newNode(arr[i]);q.add(newPair<>(node.left,newPair<>(low,node.data-1)));i++;}// Check for right childif(i<n&&arr[i]>node.data&&arr[i]<=high){node.right=newNode(arr[i]);q.add(newPair<>(node.right,newPair<>(node.data+1,high)));i++;}}returnroot;}staticvoidpreOrder(Noderoot){if(root==null)return;System.out.print(root.data+" ");preOrder(root.left);preOrder(root.right);}publicstaticvoidmain(String[]args){int[]arr={7,4,12,3,6,8,1,5,10};Noderoot=constructBst(arr);preOrder(root);}}
Python
# Python program to Construct BST from # its given level order traversalimportsysfromcollectionsimportdequeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefconstructBst(arr):n=len(arr)root=Node(arr[0])q=deque()q.append((root,(-sys.maxsize-1,sys.maxsize)))i=1whilei<nandq:curr=q.popleft()node=curr[0]low=curr[1][0]high=curr[1][1]# Check for left childifi<nandarr[i]>=lowandarr[i]<node.data:node.left=Node(arr[i])q.append((node.left,(low,node.data-1)))i+=1# Check for right childifi<nandarr[i]>node.dataandarr[i]<=high:node.right=Node(arr[i])q.append((node.right,(node.data+1,high)))i+=1returnrootdefpreOrder(root):ifnotroot:returnprint(root.data,end=" ")preOrder(root.left)preOrder(root.right)if__name__=="__main__":arr=[7,4,12,3,6,8,1,5,10]root=constructBst(arr)preOrder(root)
C#
// C# program to Construct BST from // its given level order traversalusingSystem;usingSystem.Collections.Generic;classPair<X,Y>{publicXfirst;publicYsecond;publicPair(Xfirst,Ysecond){this.first=first;this.second=second;}}classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}classGfG{staticNodeConstructBst(int[]arr){intn=arr.Length;Noderoot=newNode(arr[0]);Queue<Pair<Node,Pair<int,int>>>q=newQueue<Pair<Node,Pair<int,int>>>();q.Enqueue(newPair<Node,Pair<int,int>>(root,newPair<int,int>(int.MinValue,int.MaxValue)));inti=1;while(i<n&&q.Count>0){varcurr=q.Dequeue();Nodenode=curr.first;intlow=curr.second.first;inthigh=curr.second.second;// Check for left childif(i<n&&arr[i]>=low&&arr[i]<node.data){node.left=newNode(arr[i]);q.Enqueue(newPair<Node,Pair<int,int>>(node.left,newPair<int,int>(low,node.data-1)));i++;}// Check for right childif(i<n&&arr[i]>node.data&&arr[i]<=high){node.right=newNode(arr[i]);q.Enqueue(newPair<Node,Pair<int,int>>(node.right,newPair<int,int>(node.data+1,high)));i++;}}returnroot;}staticvoidPreOrder(Noderoot){if(root==null)return;Console.Write(root.data+" ");PreOrder(root.left);PreOrder(root.right);}staticvoidMain(){int[]arr={7,4,12,3,6,8,1,5,10};Noderoot=ConstructBst(arr);PreOrder(root);}}
JavaScript
// JavaScript program to Construct BST from // its given level order traversalclassPair{constructor(first,second){this.first=first;this.second=second;}}classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionconstructBst(arr){letn=arr.length;letroot=newNode(arr[0]);letq=[];q.push(newPair(root,newPair(-Infinity,Infinity)));leti=1;while(i<n&&q.length>0){letcurr=q.shift();letnode=curr.first;letlow=curr.second.first;lethigh=curr.second.second;// Check for left childif(i<n&&arr[i]>=low&&arr[i]<node.data){node.left=newNode(arr[i]);q.push(newPair(node.left,newPair(low,node.data-1)));i++;}// Check for right childif(i<n&&arr[i]>node.data&&arr[i]<=high){node.right=newNode(arr[i]);q.push(newPair(node.right,newPair(node.data+1,high)));i++;}}returnroot;}functionpreOrder(root){if(!root)return;process.stdout.write(root.data+" ");preOrder(root.left);preOrder(root.right);}// Driver Codeletarr=[7,4,12,3,6,8,1,5,10];letroot=constructBst(arr);preOrder(root);