Construct a tree from Inorder and Level order traversals
Last Updated : 23 Jul, 2026
Given two arrays in[] and level[] representing the inorder and level order traversals of a binary tree. Construct the binary tree and return its root.
Example:Â
Input: in[] = [4, 8, 10, 12, 14, 20, 22], level[] = [20, 8, 22, 4, 12, 10, 14] Output: [20, 8, 22, 4, 12, N, N, N, N, 10, 14] Explanation: The constructed binary tree is:
Input: in[] = [4, 2, 5], level[] = [2, 4, 5] Output: [2, 4, 5] Explanation: The constructed binary tree is:
[Naive Approach] Using Recursion - O(n^3) Time and O(n^2) Space
The idea is that first element in the level order traversal is always the root of the current subtree. Using the root's position in the inorder traversal, we determine which nodes belong to the left and right subtrees, then partition the remaining level order elements accordingly and recursively construct both subtrees.
If the current inorder range is empty, return NULL.
Take the first element of the current level order traversal as the root.
Find the root's position in the inorder traversal to identify the left and right subtree ranges.
Partition the remaining level order elements into left and right subtrees based on whether they belong to the left or right inorder range.
Recursively construct the left subtree using inorder and level order traversal.
Recursively construct the right subtree, then return the root.
C++
#include<bits/stdc++.h>usingnamespacestd;// Node of the binary tree.classNode{public:intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};// Returns the index of 'value' in inorder traversal// between indices l and r.intfindIndex(vector<int>&in,intvalue,intl,intr){for(inti=l;i<=r;i++){if(in[i]==value)returni;}return-1;}// Recursively constructs the binary tree.Node*buildTreeUtil(vector<int>&in,vector<int>&level,intl,intr){// No nodes in this subtree.if(l>r)returnnullptr;// The first node in level order is the root.Node*root=newNode(level[0]);// Find the root in inorder traversal.introotIndex=findIndex(in,level[0],l,r);// Store level order traversals of left and right subtrees.vector<int>leftLevel;vector<int>rightLevel;// Partition the remaining level order elements.for(inti=1;i<level.size();i++){intindex=findIndex(in,level[i],l,r);if(index<rootIndex)leftLevel.push_back(level[i]);elseif(index>rootIndex)rightLevel.push_back(level[i]);}// Construct left and right subtrees recursively.root->left=buildTreeUtil(in,leftLevel,l,rootIndex-1);root->right=buildTreeUtil(in,rightLevel,rootIndex+1,r);returnroot;}// Constructs the binary tree from inorder and level order traversals.Node*buildTree(vector<int>&in,vector<int>&level){returnbuildTreeUtil(in,level,0,in.size()-1);}// Prints inorder traversal of the constructed tree.voidprintLevelOrder(Node*root){if(root==nullptr)return;vector<string>ans;queue<Node*>q;q.push(root);while(!q.empty()){Node*curr=q.front();q.pop();if(curr==nullptr){ans.push_back("N");}else{ans.push_back(to_string(curr->data));q.push(curr->left);q.push(curr->right);}}// Remove trailing nulls.while(!ans.empty()&&ans.back()=="N")ans.pop_back();for(string&x:ans)cout<<x<<" ";cout<<'\n';}intmain(){vector<int>in={4,8,10,12,14,20,22};vector<int>level={20,8,22,4,12,10,14};Node*root=buildTree(in,level);printLevelOrder(root);return0;}
Java
importjava.util.*;// Node of the binary tree.classNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}classGFG{// Returns the index of 'value' in inorder traversal// between indices l and r.staticintfindIndex(int[]in,intvalue,intl,intr){for(inti=l;i<=r;i++){if(in[i]==value)returni;}return-1;}// Recursively constructs the binary tree.staticNodebuildTreeUtil(int[]in,int[]level,intl,intr){// No nodes in this subtree.if(l>r)returnnull;// The first node in level order is the root.Noderoot=newNode(level[0]);// Find the root in inorder traversal.introotIndex=findIndex(in,level[0],l,r);// Store level order traversals of left and right// subtrees.intleftSize=rootIndex-l;intrightSize=r-rootIndex;int[]leftLevel=newint[leftSize];int[]rightLevel=newint[rightSize];intleftPtr=0;intrightPtr=0;// Partition the remaining level order elements.for(inti=1;i<level.length;i++){intindex=findIndex(in,level[i],l,r);if(index<rootIndex)leftLevel[leftPtr++]=level[i];elseif(index>rootIndex)rightLevel[rightPtr++]=level[i];}// Construct left and right subtrees recursively.root.left=buildTreeUtil(in,leftLevel,l,rootIndex-1);root.right=buildTreeUtil(in,rightLevel,rootIndex+1,r);returnroot;}// Constructs the binary tree from inorder and level// order traversals.staticNodebuildTree(int[]in,int[]level){returnbuildTreeUtil(in,level,0,in.length-1);}// Prints the tree in level order using 'N' for null// nodes.staticvoidprintLevelOrder(Noderoot){if(root==null)return;ArrayList<String>ans=newArrayList<>();Queue<Node>q=newLinkedList<>();q.offer(root);while(!q.isEmpty()){Nodecurr=q.poll();if(curr==null){ans.add("N");}else{ans.add(String.valueOf(curr.data));q.offer(curr.left);q.offer(curr.right);}}// Remove trailing nulls.while(!ans.isEmpty()&&ans.get(ans.size()-1).equals("N"))ans.remove(ans.size()-1);for(Strings:ans)System.out.print(s+" ");System.out.println();}publicstaticvoidmain(String[]args){int[]in={4,8,10,12,14,20,22};int[]level={20,8,22,4,12,10,14};Noderoot=buildTree(in,level);printLevelOrder(root);}}
Python
fromcollectionsimportdeque# Node of the binary tree.classNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Returns the index of 'value' in inorder traversal# between indices l and r.deffindIndex(inorder,value,l,r):foriinrange(l,r+1):ifinorder[i]==value:returnireturn-1# Recursively constructs the binary tree.defbuildTreeUtil(inorder,level,l,r):# No nodes in this subtree.ifl>r:returnNone# The first node in level order is the root.root=Node(level[0])# Find the root in inorder traversal.rootIndex=findIndex(inorder,level[0],l,r)# Store level order traversals of left and right subtrees.leftLevel=[]rightLevel=[]# Partition the remaining level order elements.foriinrange(1,len(level)):index=findIndex(inorder,level[i],l,r)ifindex<rootIndex:leftLevel.append(level[i])elifindex>rootIndex:rightLevel.append(level[i])# Construct left and right subtrees recursively.root.left=buildTreeUtil(inorder,leftLevel,l,rootIndex-1)root.right=buildTreeUtil(inorder,rightLevel,rootIndex+1,r)returnroot# Constructs the binary tree from inorder and level order traversals.defbuildTree(inorder,level):returnbuildTreeUtil(inorder,level,0,len(inorder)-1)# Prints the tree in level order using 'N' for null nodes.defprintLevelOrder(root):ifrootisNone:returnans=[]q=deque([root])whileq:curr=q.popleft()ifcurrisNone:ans.append("N")else:ans.append(str(curr.data))q.append(curr.left)q.append(curr.right)# Remove trailing nulls.whileansandans[-1]=="N":ans.pop()print(*ans)# Driver codeif__name__=="__main__":inorder=[4,8,10,12,14,20,22]level=[20,8,22,4,12,10,14]root=buildTree(inorder,level)printLevelOrder(root)
C#
usingSystem;usingSystem.Collections.Generic;// Node of the binary tree.classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGFG{// Returns the index of 'value' in inorder traversal// between indices l and r.staticintFindIndex(int[]inorder,intvalue,intl,intr){for(inti=l;i<=r;i++){if(inorder[i]==value)returni;}return-1;}// Recursively constructs the binary tree.staticNodeBuildTreeUtil(int[]inorder,int[]level,intl,intr){// No nodes in this subtree.if(l>r)returnnull;// The first node in level order is the root.Noderoot=newNode(level[0]);// Find the root in inorder traversal.introotIndex=FindIndex(inorder,level[0],l,r);// Store level order traversals of left and right// subtrees.intleftSize=rootIndex-l;intrightSize=r-rootIndex;int[]leftLevel=newint[leftSize];int[]rightLevel=newint[rightSize];intleftPtr=0;intrightPtr=0;// Partition the remaining level order elements.for(inti=1;i<level.Length;i++){intindex=FindIndex(inorder,level[i],l,r);if(index<rootIndex)leftLevel[leftPtr++]=level[i];elseif(index>rootIndex)rightLevel[rightPtr++]=level[i];}// Construct left and right subtrees recursively.root.left=BuildTreeUtil(inorder,leftLevel,l,rootIndex-1);root.right=BuildTreeUtil(inorder,rightLevel,rootIndex+1,r);returnroot;}// Constructs the binary tree from inorder and level// order traversals.staticNodebuildTree(int[]inorder,int[]level){returnBuildTreeUtil(inorder,level,0,inorder.Length-1);}// Prints the tree in level order using 'N' for null// nodes.staticvoidPrintLevelOrder(Noderoot){if(root==null)return;List<string>ans=newList<string>();Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodecurr=q.Dequeue();if(curr==null){ans.Add("N");}else{ans.Add(curr.data.ToString());q.Enqueue(curr.left);q.Enqueue(curr.right);}}// Remove trailing nulls.while(ans.Count>0&&ans[ans.Count-1]=="N")ans.RemoveAt(ans.Count-1);foreach(stringxinans)Console.Write(x+" ");Console.WriteLine();}staticvoidMain(){int[]inorder={4,8,10,12,14,20,22};int[]level={20,8,22,4,12,10,14};Noderoot=buildTree(inorder,level);PrintLevelOrder(root);}}
JavaScript
// Node of the binary tree.classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Returns the index of 'value' in inorder traversal// between indices l and r.functionfindIndex(inorder,value,l,r){for(leti=l;i<=r;i++){if(inorder[i]===value)returni;}return-1;}// Recursively constructs the binary tree.functionbuildTreeUtil(inorder,level,l,r){// No nodes in this subtree.if(l>r)returnnull;// The first node in level order is the root.letroot=newNode(level[0]);// Find the root in inorder traversal.letrootIndex=findIndex(inorder,level[0],l,r);// Store level order traversals of left and right// subtrees.letleftLevel=[];letrightLevel=[];// Partition the remaining level order elements.for(leti=1;i<level.length;i++){letindex=findIndex(inorder,level[i],l,r);if(index<rootIndex)leftLevel.push(level[i]);elseif(index>rootIndex)rightLevel.push(level[i]);}// Construct left and right subtrees recursively.root.left=buildTreeUtil(inorder,leftLevel,l,rootIndex-1);root.right=buildTreeUtil(inorder,rightLevel,rootIndex+1,r);returnroot;}// Constructs the binary tree from inorder and level order// traversals.functionbuildTree(inorder,level){returnbuildTreeUtil(inorder,level,0,inorder.length-1);}// Prints the tree in level order using 'N' for null nodes.functionprintLevelOrder(root){if(root===null)return;letans=[];letq=[];q.push(root);while(q.length>0){letcurr=q.shift();if(curr===null){ans.push("N");}else{ans.push(curr.data.toString());q.push(curr.left);q.push(curr.right);}}// Remove trailing nulls.while(ans.length>0&&ans[ans.length-1]==="N")ans.pop();console.log(ans.join(" "));}// Driver codeletinorder=[4,8,10,12,14,20,22];letlevel=[20,8,22,4,12,10,14];letroot=buildTree(inorder,level);printLevelOrder(root);
Output
20 8 22 4 12 N N N N 10 14
[Better Approach] Using Recursion With Hash map - O(n^2) Time and O(n^2) Space
The idea is the same as the previous approach, but we use a hash to speed up the construction. A hash map stores the index of each node in the inorder traversal, allowing the root's position to be found in O(1) time. Alternatively, a hash set can be used to quickly determine whether a node belongs to the left subtree after locating the root in the inorder traversal.
Store the index of each node in the inorder traversal using a hash map for O(1) lookup.
Take the first element of the current level order traversal as the root.
Use the hash map to find the root's position in the inorder traversal, which divides the left and right subtree ranges.
Partition the remaining level order elements into left and right subtrees based on their inorder indices.
Recursively construct the left subtree using inorder and level order traversal.
Recursively construct the right subtree, then return the root.
C++
#include<bits/stdc++.h>usingnamespacestd;// Node of the binary tree.classNode{public:intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};// Recursively constructs the binary tree.Node*buildTreeUtil(constunordered_map<int,int>&inMap,vector<int>&level,intl,intr){// No nodes in this subtree.if(l>r)returnnullptr;// The first element of level order is the root.Node*root=newNode(level[0]);// Find the root's position in inorder traversal.introotIndex=inMap.at(level[0]);// Store level order traversals of left and right subtrees.vector<int>leftLevel;vector<int>rightLevel;// Partition the remaining level order elements.for(inti=1;i<level.size();i++){if(inMap.at(level[i])<rootIndex)leftLevel.push_back(level[i]);elserightLevel.push_back(level[i]);}// Construct left and right subtrees recursively.root->left=buildTreeUtil(inMap,leftLevel,l,rootIndex-1);root->right=buildTreeUtil(inMap,rightLevel,rootIndex+1,r);returnroot;}// Constructs the binary tree from inorder and level order traversals.Node*buildTree(vector<int>&in,vector<int>&level){// Store the index of every node in inorder traversal.unordered_map<int,int>inMap;for(inti=0;i<in.size();i++)inMap[in[i]]=i;returnbuildTreeUtil(inMap,level,0,in.size()-1);}// Prints the tree in level order using 'N' for null nodes.voidprintLevelOrder(Node*root){if(root==nullptr)return;vector<string>ans;queue<Node*>q;q.push(root);while(!q.empty()){Node*curr=q.front();q.pop();if(curr==nullptr){ans.push_back("N");}else{ans.push_back(to_string(curr->data));q.push(curr->left);q.push(curr->right);}}// Remove trailing null nodes.while(!ans.empty()&&ans.back()=="N")ans.pop_back();for(string&x:ans)cout<<x<<" ";cout<<'\n';}intmain(){vector<int>in={4,8,10,12,14,20,22};vector<int>level={20,8,22,4,12,10,14};Node*root=buildTree(in,level);printLevelOrder(root);return0;}
Java
importjava.util.*;// Node of the binary tree.classNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}publicclassGFG{// Recursively constructs the binary tree.staticNodebuildTreeUtil(HashMap<Integer,Integer>inMap,int[]level,intl,intr){// No nodes in this subtree.if(l>r)returnnull;// The first element of level order is the root.Noderoot=newNode(level[0]);// Find the root's position in inorder traversal.introotIndex=inMap.get(level[0]);// Store level order traversals of left and right// subtrees.ArrayList<Integer>leftList=newArrayList<>();ArrayList<Integer>rightList=newArrayList<>();// Partition the remaining level order elements.for(inti=1;i<level.length;i++){if(inMap.get(level[i])<rootIndex)leftList.add(level[i]);elserightList.add(level[i]);}// Convert ArrayLists into arrays.int[]leftLevel=newint[leftList.size()];int[]rightLevel=newint[rightList.size()];for(inti=0;i<leftList.size();i++)leftLevel[i]=leftList.get(i);for(inti=0;i<rightList.size();i++)rightLevel[i]=rightList.get(i);// Construct left and right subtrees recursively.root.left=buildTreeUtil(inMap,leftLevel,l,rootIndex-1);root.right=buildTreeUtil(inMap,rightLevel,rootIndex+1,r);returnroot;}// Constructs the binary tree from inorder and level// order traversals.staticNodebuildTree(int[]in,int[]level){// Store the index of every node in inorder// traversal.HashMap<Integer,Integer>inMap=newHashMap<>();for(inti=0;i<in.length;i++)inMap.put(in[i],i);returnbuildTreeUtil(inMap,level,0,in.length-1);}// Prints the tree in level order using 'N' for null// nodes.staticvoidprintLevelOrder(Noderoot){if(root==null)return;ArrayList<String>ans=newArrayList<>();Queue<Node>q=newLinkedList<>();q.offer(root);while(!q.isEmpty()){Nodecurr=q.poll();if(curr==null){ans.add("N");}else{ans.add(String.valueOf(curr.data));q.offer(curr.left);q.offer(curr.right);}}// Remove trailing null nodes.while(!ans.isEmpty()&&ans.get(ans.size()-1).equals("N"))ans.remove(ans.size()-1);for(Stringx:ans)System.out.print(x+" ");System.out.println();}publicstaticvoidmain(String[]args){int[]in={4,8,10,12,14,20,22};int[]level={20,8,22,4,12,10,14};Noderoot=buildTree(in,level);printLevelOrder(root);}}
Python
fromcollectionsimportdeque# Node of the binary tree.classNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Recursively constructs the binary tree.defbuildTreeUtil(inMap,level,l,r):# No nodes in this subtree.ifl>r:returnNone# The first element of level order is the root.root=Node(level[0])# Find the root's position in inorder traversal.rootIndex=inMap[level[0]]# Store level order traversals of left and right subtrees.leftLevel=[]rightLevel=[]# Partition the remaining level order elements.foriinrange(1,len(level)):ifinMap[level[i]]<rootIndex:leftLevel.append(level[i])else:rightLevel.append(level[i])# Construct left and right subtrees recursively.root.left=buildTreeUtil(inMap,leftLevel,l,rootIndex-1)root.right=buildTreeUtil(inMap,rightLevel,rootIndex+1,r)returnroot# Constructs the binary tree from inorder and level order traversals.defbuildTree(inorder,level):# Store the index of every node in inorder traversal.inMap={}foriinrange(len(inorder)):inMap[inorder[i]]=ireturnbuildTreeUtil(inMap,level,0,len(inorder)-1)# Prints the tree in level order using 'N' for null nodes.defprintLevelOrder(root):ifrootisNone:returnans=[]q=deque([root])whileq:curr=q.popleft()ifcurrisNone:ans.append("N")else:ans.append(str(curr.data))q.append(curr.left)q.append(curr.right)# Remove trailing null nodes.whileansandans[-1]=="N":ans.pop()print(*ans)# Driver codeif__name__=="__main__":inorder=[4,8,10,12,14,20,22]level=[20,8,22,4,12,10,14]root=buildTree(inorder,level)printLevelOrder(root)
C#
usingSystem;usingSystem.Collections.Generic;// Node of the binary tree.classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGFG{// Recursively constructs the binary tree.staticNodeBuildTreeUtil(Dictionary<int,int>inMap,int[]level,intl,intr){// No nodes in this subtree.if(l>r)returnnull;// The first element of level order is the root.Noderoot=newNode(level[0]);// Find the root's position in inorder traversal.introotIndex=inMap[level[0]];// Store level order traversals of left and right// subtrees.List<int>leftList=newList<int>();List<int>rightList=newList<int>();// Partition the remaining level order elements.for(inti=1;i<level.Length;i++){if(inMap[level[i]]<rootIndex)leftList.Add(level[i]);elserightList.Add(level[i]);}// Convert lists into arrays.int[]leftLevel=leftList.ToArray();int[]rightLevel=rightList.ToArray();// Construct left and right subtrees recursively.root.left=BuildTreeUtil(inMap,leftLevel,l,rootIndex-1);root.right=BuildTreeUtil(inMap,rightLevel,rootIndex+1,r);returnroot;}// Constructs the binary tree from inorder and level// order traversals.staticNodebuildTree(int[]inorder,int[]level){// Store the index of every node in inorder// traversal.Dictionary<int,int>inMap=newDictionary<int,int>();for(inti=0;i<inorder.Length;i++)inMap[inorder[i]]=i;returnBuildTreeUtil(inMap,level,0,inorder.Length-1);}// Prints the tree in level order using 'N' for null// nodes.staticvoidPrintLevelOrder(Noderoot){if(root==null)return;List<string>ans=newList<string>();Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodecurr=q.Dequeue();if(curr==null){ans.Add("N");}else{ans.Add(curr.data.ToString());q.Enqueue(curr.left);q.Enqueue(curr.right);}}// Remove trailing null nodes.while(ans.Count>0&&ans[ans.Count-1]=="N")ans.RemoveAt(ans.Count-1);foreach(stringxinans)Console.Write(x+" ");Console.WriteLine();}staticvoidMain(){int[]inorder={4,8,10,12,14,20,22};int[]level={20,8,22,4,12,10,14};Noderoot=buildTree(inorder,level);PrintLevelOrder(root);}}
JavaScript
// Node of the binary tree.classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Recursively constructs the binary tree.functionbuildTreeUtil(inMap,level,l,r){// No nodes in this subtree.if(l>r)returnnull;// The first element of level order is the root.letroot=newNode(level[0]);// Find the root's position in inorder traversal.letrootIndex=inMap.get(level[0]);// Store level order traversals of left and right// subtrees.letleftLevel=[];letrightLevel=[];// Partition the remaining level order elements.for(leti=1;i<level.length;i++){if(inMap.get(level[i])<rootIndex)leftLevel.push(level[i]);elserightLevel.push(level[i]);}// Construct left and right subtrees recursively.root.left=buildTreeUtil(inMap,leftLevel,l,rootIndex-1);root.right=buildTreeUtil(inMap,rightLevel,rootIndex+1,r);returnroot;}// Constructs the binary tree from inorder and level order// traversals.functionbuildTree(inorder,level){// Store the index of every node in inorder traversal.letinMap=newMap();for(leti=0;i<inorder.length;i++)inMap.set(inorder[i],i);returnbuildTreeUtil(inMap,level,0,inorder.length-1);}// Prints the tree in level order using 'N' for null nodes.functionprintLevelOrder(root){if(root===null)return;letans=[];letq=[];q.push(root);while(q.length>0){letcurr=q.shift();if(curr===null){ans.push("N");}else{ans.push(curr.data.toString());q.push(curr.left);q.push(curr.right);}}// Remove trailing null nodes.while(ans.length>0&&ans[ans.length-1]==="N")ans.pop();console.log(ans.join(" "));}// Driver codeletinorder=[4,8,10,12,14,20,22];letlevel=[20,8,22,4,12,10,14];letroot=buildTree(inorder,level);printLevelOrder(root);
Output
20 8 22 4 12 N N N N 10 14
[Expected Approach] Using Queue and Hash map - O(n) Time and O(n) Space
The idea is to process the nodes in the same order as they appear in the level order traversal. The first element of the level order array becomes the root. For every node, we maintain its valid inorder range. Using the root's index in the inorder array, we determine whether its left and right subtrees exist. If they do, the next unused elements in the level order traversal become the roots of those subtrees, and they are processed similarly using a queue.
Store the index of every node in the inorder traversal using a hash map for O(1) index lookup.
Create the root from the first element of the level order traversal and push it into a queue along with its inorder range.
Process each node from the queue and find its position in the inorder traversal using the hash map.
If a left subtree exists, create its root using the next unused level order element and push it into the queue with its inorder range.
If a right subtree exists, create its root using the next unused level order element and push it into the queue with its inorder range.
Continue until the queue becomes empty, then return the constructed root.
C++
#include<bits/stdc++.h>usingnamespacestd;// Node of the binary tree.classNode{public:intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};// Constructs the binary tree from inorder and level order traversals.Node*buildTree(vector<int>&in,vector<int>&level){intn=in.size();// Empty tree.if(n==0)returnnullptr;// Store the index of every node in inorder traversal.unordered_map<int,int>inMap;for(inti=0;i<n;i++)inMap[in[i]]=i;// Create the root node.Node*root=newNode(level[0]);// Points to the next unused element in level order traversal.intindex=1;// Queue stores:// {current node, left inorder index, right inorder index}queue<tuple<Node*,int,int>>q;q.push({root,0,n-1});// Construct the tree in level order.while(!q.empty()){auto[node,left,right]=q.front();q.pop();// Position of the current node in inorder traversal.introotIndex=inMap[node->data];// If the left subtree exists, the next unused level order// element becomes its root.if(left<rootIndex&&index<n){node->left=newNode(level[index++]);q.push({node->left,left,rootIndex-1});}// If the right subtree exists, the next unused level order// element becomes its root.if(rootIndex<right&&index<n){node->right=newNode(level[index++]);q.push({node->right,rootIndex+1,right});}}returnroot;}// Prints the tree in level order using 'N' for null nodes.voidprintLevelOrder(Node*root){if(root==nullptr)return;vector<string>ans;queue<Node*>q;q.push(root);while(!q.empty()){Node*curr=q.front();q.pop();if(curr==nullptr){ans.push_back("N");}else{ans.push_back(to_string(curr->data));q.push(curr->left);q.push(curr->right);}}// Remove trailing null nodes.while(!ans.empty()&&ans.back()=="N")ans.pop_back();for(string&x:ans)cout<<x<<" ";cout<<'\n';}intmain(){vector<int>in={4,8,10,12,14,20,22};vector<int>level={20,8,22,4,12,10,14};Node*root=buildTree(in,level);printLevelOrder(root);return0;}
Java
importjava.util.*;// Node of the binary tree.classNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}publicclassGFG{// Constructs the binary tree from inorder and level// order traversals.staticNodebuildTree(int[]in,int[]level){intn=in.length;// Empty tree.if(n==0)returnnull;// Store the index of every node in inorder// traversal.HashMap<Integer,Integer>inMap=newHashMap<>();for(inti=0;i<n;i++)inMap.put(in[i],i);// Create the root node.Noderoot=newNode(level[0]);// Points to the next unused element in level order// traversal.intindex=1;// Queue stores:// {current node, left inorder index, right inorder// index}Queue<Object[]>q=newLinkedList<>();q.offer(newObject[]{root,0,n-1});// Construct the tree in level order.while(!q.isEmpty()){Object[]curr=q.poll();Nodenode=(Node)curr[0];intleft=(Integer)curr[1];intright=(Integer)curr[2];// Position of the current node in inorder// traversal.introotIndex=inMap.get(node.data);// If the left subtree exists, the next unused// level order element becomes its root.if(left<rootIndex&&index<n){node.left=newNode(level[index++]);q.offer(newObject[]{node.left,left,rootIndex-1});}// If the right subtree exists, the next unused// level order element becomes its root.if(rootIndex<right&&index<n){node.right=newNode(level[index++]);q.offer(newObject[]{node.right,rootIndex+1,right});}}returnroot;}// Prints the tree in level order using 'N' for null// nodes.staticvoidprintLevelOrder(Noderoot){if(root==null)return;ArrayList<String>ans=newArrayList<>();Queue<Node>q=newLinkedList<>();q.offer(root);while(!q.isEmpty()){Nodecurr=q.poll();if(curr==null){ans.add("N");}else{ans.add(String.valueOf(curr.data));q.offer(curr.left);q.offer(curr.right);}}// Remove trailing null nodes.while(!ans.isEmpty()&&ans.get(ans.size()-1).equals("N"))ans.remove(ans.size()-1);for(Stringx:ans)System.out.print(x+" ");System.out.println();}publicstaticvoidmain(String[]args){int[]in={4,8,10,12,14,20,22};int[]level={20,8,22,4,12,10,14};Noderoot=buildTree(in,level);printLevelOrder(root);}}
Python
fromcollectionsimportdeque# Node of the binary tree.classNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Constructs the binary tree from inorder and level# order traversals.defbuildTree(inorder,level):n=len(inorder)# Empty tree.ifn==0:returnNone# Store the index of every node in inorder traversal.inMap={}foriinrange(n):inMap[inorder[i]]=i# Create the root node.root=Node(level[0])# Points to the next unused element in level order traversal.index=1# Queue stores:# (current node, left inorder index, right inorder index)q=deque()q.append((root,0,n-1))# Construct the tree in level order.whileq:node,left,right=q.popleft()# Position of the current node in inorder traversal.rootIndex=inMap[node.data]# If the left subtree exists, the next unused level order# element becomes its root.ifleft<rootIndexandindex<n:node.left=Node(level[index])index+=1q.append((node.left,left,rootIndex-1))# If the right subtree exists, the next unused level order# element becomes its root.ifrootIndex<rightandindex<n:node.right=Node(level[index])index+=1q.append((node.right,rootIndex+1,right))returnroot# Prints the tree in level order using 'N' for null nodes.defprintLevelOrder(root):ifrootisNone:returnans=[]q=deque([root])whileq:curr=q.popleft()ifcurrisNone:ans.append("N")else:ans.append(str(curr.data))q.append(curr.left)q.append(curr.right)# Remove trailing null nodes.whileansandans[-1]=="N":ans.pop()print(*ans)# Driver codeif__name__=="__main__":inorder=[4,8,10,12,14,20,22]level=[20,8,22,4,12,10,14]root=buildTree(inorder,level)printLevelOrder(root)
C#
usingSystem;usingSystem.Collections.Generic;// Node of the binary tree.classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGFG{// Constructs the binary tree from inorder and level// order traversals.staticNodebuildTree(int[]inorder,int[]level){intn=inorder.Length;// Empty tree.if(n==0)returnnull;// Store the index of every node in inorder// traversal.Dictionary<int,int>inMap=newDictionary<int,int>();for(inti=0;i<n;i++)inMap[inorder[i]]=i;// Create the root node.Noderoot=newNode(level[0]);// Points to the next unused element in level order// traversal.intindex=1;// Queue stores:// (current node, left inorder index, right inorder// index)Queue<(Nodenode,intleft,intright)>q=newQueue<(Nodenode,intleft,intright)>();q.Enqueue((root,0,n-1));// Construct the tree in level order.while(q.Count>0){varcurr=q.Dequeue();Nodenode=curr.node;intleft=curr.left;intright=curr.right;// Position of the current node in inorder// traversal.introotIndex=inMap[node.data];// If the left subtree exists, the next unused// level order element becomes its root.if(left<rootIndex&&index<n){node.left=newNode(level[index++]);q.Enqueue((node.left,left,rootIndex-1));}// If the right subtree exists, the next unused// level order element becomes its root.if(rootIndex<right&&index<n){node.right=newNode(level[index++]);q.Enqueue((node.right,rootIndex+1,right));}}returnroot;}// Prints the tree in level order using 'N' for null// nodes.staticvoidPrintLevelOrder(Noderoot){if(root==null)return;List<string>ans=newList<string>();Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodecurr=q.Dequeue();if(curr==null){ans.Add("N");}else{ans.Add(curr.data.ToString());q.Enqueue(curr.left);q.Enqueue(curr.right);}}// Remove trailing null nodes.while(ans.Count>0&&ans[ans.Count-1]=="N")ans.RemoveAt(ans.Count-1);foreach(stringxinans)Console.Write(x+" ");Console.WriteLine();}staticvoidMain(){int[]inorder={4,8,10,12,14,20,22};int[]level={20,8,22,4,12,10,14};Noderoot=buildTree(inorder,level);PrintLevelOrder(root);}}
JavaScript
// Node of the binary tree.classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Constructs the binary tree from inorder and level// order traversals.functionbuildTree(inorder,level){constn=inorder.length;// Empty tree.if(n===0)returnnull;// Store the index of every node in inorder traversal.constinMap=newMap();for(leti=0;i<n;i++)inMap.set(inorder[i],i);// Create the root node.constroot=newNode(level[0]);// Points to the next unused element in level order// traversal.letindex=1;// Queue stores:// [current node, left inorder index, right inorder// index]constq=[];q.push([root,0,n-1]);// Construct the tree in level order.while(q.length>0){const[node,left,right]=q.shift();// Position of the current node in inorder// traversal.constrootIndex=inMap.get(node.data);// If the left subtree exists, the next unused level// order element becomes its root.if(left<rootIndex&&index<n){node.left=newNode(level[index++]);q.push([node.left,left,rootIndex-1]);}// If the right subtree exists, the next unused// level order element becomes its root.if(rootIndex<right&&index<n){node.right=newNode(level[index++]);q.push([node.right,rootIndex+1,right]);}}returnroot;}// Prints the tree in level order using 'N' for null nodes.functionprintLevelOrder(root){if(root===null)return;constans=[];constq=[];q.push(root);while(q.length>0){constcurr=q.shift();if(curr===null){ans.push("N");}else{ans.push(curr.data.toString());q.push(curr.left);q.push(curr.right);}}// Remove trailing null nodes.while(ans.length>0&&ans[ans.length-1]==="N")ans.pop();console.log(ans.join(" "));}// Driver codeconstinorder=[4,8,10,12,14,20,22];constlevel=[20,8,22,4,12,10,14];constroot=buildTree(inorder,level);printLevelOrder(root);