[Naive Approach] Using Pre-order traversal - O(n^2) Time and O(h) Space
The idea is to construct the tree using pre-order traversal. Take the first element of the pre-order array and create root node. Find the index of this node in the in-order array. Create the left subtree using the elements present on left side of root node in in-order array. Similarly create the right subtree using the elements present on the right side of the root node in in-order array.
C++
//Driver Code Starts// c++ program to construct tree using// inorder and preorder traversals#include<iostream>#include<queue>#include<vector>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Print tree as level ordervoidprintLevelOrder(Node*root){if(root==nullptr){cout<<"N ";return;}queue<Node*>qq;qq.push(root);intnonNull=1;while(!qq.empty()&&nonNull>0){Node*curr=qq.front();qq.pop();if(curr==nullptr){cout<<"N ";continue;}nonNull--;cout<<(curr->data)<<" ";qq.push(curr->left);qq.push(curr->right);if(curr->left)nonNull++;if(curr->right)nonNull++;}}//Driver Code Ends// Function to find the index of an element in the array.intsearch(vector<int>&inorder,intvalue,intleft,intright){for(inti=left;i<=right;i++){if(inorder[i]==value)returni;}return-1;}// Recursive function to build the binary tree.Node*buildTreeRecur(vector<int>&inorder,vector<int>&preorder,int&preIndex,intleft,intright){// For empty inorder array, return nullif(left>right)returnnullptr;introotVal=preorder[preIndex];preIndex++;// create the root NodeNode*root=newNode(rootVal);// find the index of Root element in the in-order array.intindex=search(inorder,rootVal,left,right);// Recursively create the left and right subtree.root->left=buildTreeRecur(inorder,preorder,preIndex,left,index-1);root->right=buildTreeRecur(inorder,preorder,preIndex,index+1,right);returnroot;}// Function to construct tree from its inorder and preorder traversalsNode*buildTree(vector<int>&inorder,vector<int>&preorder){intpreIndex=0;Node*root=buildTreeRecur(inorder,preorder,preIndex,0,preorder.size()-1);returnroot;}//Driver Code Startsintmain(){vector<int>inorder={3,1,4,0,5,2};vector<int>preorder={0,1,3,4,2,5};Node*root=buildTree(inorder,preorder);printLevelOrder(root);return0;}//Driver Code Ends
Java
//Driver Code Starts// Java program to construct tree using // inorder and preorder traversalsimportjava.util.Queue;importjava.util.LinkedList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Print tree as level orderstaticvoidprintLevelOrder(Noderoot){if(root==null){System.out.print("N ");return;}Queue<Node>queue=newLinkedList<>();queue.add(root);intnonNull=1;while(!queue.isEmpty()&&nonNull>0){Nodecurr=queue.poll();if(curr==null){System.out.print("N ");continue;}nonNull--;System.out.print(curr.data+" ");queue.add(curr.left);queue.add(curr.right);if(curr.left!=null)nonNull++;if(curr.right!=null)nonNull++;}}//Driver Code Ends// Function to find the index of an element in the array.staticintsearch(int[]inorder,intvalue,intleft,intright){for(inti=left;i<=right;i++){if(inorder[i]==value)returni;}return-1;}// Recursive function to build the binary tree.staticNodebuildTreeRecur(int[]inorder,int[]preorder,int[]preIndex,intleft,intright){// For empty inorder array, return nullif(left>right)returnnull;introotVal=preorder[preIndex[0]];preIndex[0]++;// create the root NodeNoderoot=newNode(rootVal);// find the index of Root element in the in-order array.intindex=search(inorder,rootVal,left,right);// Recursively create the left and right subtree.root.left=buildTreeRecur(inorder,preorder,preIndex,left,index-1);root.right=buildTreeRecur(inorder,preorder,preIndex,index+1,right);returnroot;}// Function to construct tree from its inorder and preorder traversalsstaticNodebuildTree(int[]inorder,int[]preorder){int[]preIndex={0};returnbuildTreeRecur(inorder,preorder,preIndex,0,preorder.length-1);}//Driver Code Startspublicstaticvoidmain(String[]args){int[]inorder={3,1,4,0,5,2};int[]preorder={0,1,3,4,2,5};Noderoot=buildTree(inorder,preorder);printLevelOrder(root);}}//Driver Code Ends
Python
#Driver Code Starts# Python program to construct tree using # inorder and preorder traversalsfromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Print tree as level orderdefprintLevelOrder(root):ifrootisNone:print("N ",end="")returnqueue=deque([root])non_null=1whilequeueandnon_null>0:curr=queue.popleft()ifcurrisNone:print("N ",end="")continuenon_null-=1print(curr.data,end=" ")queue.append(curr.left)queue.append(curr.right)ifcurr.left:non_null+=1ifcurr.right:non_null+=1#Driver Code Ends# Function to find the index of an element in the arraydefsearch(inorder,value,left,right):foriinrange(left,right+1):ifinorder[i]==value:returnireturn-1# Recursive function to build the binary tree.defbuildTreeRecur(inorder,preorder,preIndex,left,right):# For empty inorder array, return nullifleft>right:returnNonerootVal=preorder[preIndex[0]]preIndex[0]+=1# create the root Noderoot=Node(rootVal)# find the index of Root element in the in-order array.index=search(inorder,rootVal,left,right)# Recursively create the left and right subtree.root.left=buildTreeRecur(inorder,preorder,preIndex,left,index-1)root.right=buildTreeRecur(inorder,preorder,preIndex,index+1,right)returnroot# Function to construct tree from its inorder and preorder traversalsdefbuildTree(inorder,preorder):preIndex=[0]returnbuildTreeRecur(inorder,preorder,preIndex,0,len(preorder)-1)#Driver Code Startsif__name__=="__main__":inorder=[3,1,4,0,5,2]preorder=[0,1,3,4,2,5]root=buildTree(inorder,preorder)printLevelOrder(root)#Driver Code Ends
C#
//Driver Code Starts// C# program to construct tree using // inorder and preorder traversalsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Print tree as level orderstaticvoidPrintLevelOrder(Noderoot){if(root==null){Console.Write("N ");return;}Queue<Node>queue=newQueue<Node>();queue.Enqueue(root);intnonNull=1;while(queue.Count>0&&nonNull>0){Nodecurr=queue.Dequeue();if(curr==null){Console.Write("N ");continue;}nonNull--;Console.Write(curr.data+" ");queue.Enqueue(curr.left);queue.Enqueue(curr.right);if(curr.left!=null)nonNull++;if(curr.right!=null)nonNull++;}}//Driver Code Ends// Function to find the index of an element in the arraystaticintSearch(int[]inorder,intvalue,intleft,intright){for(inti=left;i<=right;i++){if(inorder[i]==value)returni;}return-1;}// Recursive function to build the binary tree.staticNodeBuildTreeRecur(int[]inorder,int[]preorder,refintpreIndex,intleft,intright){// For empty inorder array, return nullif(left>right)returnnull;introotVal=preorder[preIndex];preIndex++;// create the root NodeNoderoot=newNode(rootVal);// find the index of Root element in the in-order array.intindex=Search(inorder,rootVal,left,right);// Recursively create the left and right subtree.root.left=BuildTreeRecur(inorder,preorder,refpreIndex,left,index-1);root.right=BuildTreeRecur(inorder,preorder,refpreIndex,index+1,right);returnroot;}// Function to construct tree from its inorder and preorder traversalsstaticNodeBuildTree(int[]inorder,int[]preorder){intpreIndex=0;returnBuildTreeRecur(inorder,preorder,refpreIndex,0,preorder.Length-1);}//Driver Code StartsstaticvoidMain(string[]args){int[]inorder={3,1,4,0,5,2};int[]preorder={0,1,3,4,2,5};Noderoot=BuildTree(inorder,preorder);PrintLevelOrder(root);}}//Driver Code Ends
JavaScript
//Driver Code Starts// JavaScript program to construct tree using // inorder and preorder traversalsclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Print tree as level orderfunctionprintLevelOrder(root){if(root===null){process.stdout.write("N ");return;}constqueue=[];queue.push(root);letnonNull=1;while(queue.length>0&&nonNull>0){constcurr=queue.shift();if(curr===null){process.stdout.write("N ");continue;}nonNull--;process.stdout.write(curr.data+" ");queue.push(curr.left);queue.push(curr.right);if(curr.left)nonNull++;if(curr.right)nonNull++;}}//Driver Code Ends// Function to find the index of an element in the arrayfunctionsearch(inorder,value,left,right){for(leti=left;i<=right;i++){if(inorder[i]===value)returni;}return-1;}// Recursive function to build the binary tree.functionbuildTreeRecur(inorder,preorder,preIndex,left,right){// For empty inorder array, return nullif(left>right)returnnull;constrootVal=preorder[preIndex[0]];preIndex[0]++;// create the root Nodeconstroot=newNode(rootVal);// find the index of Root element in the in-order array.constindex=search(inorder,rootVal,left,right);// Recursively create the left and right subtree.root.left=buildTreeRecur(inorder,preorder,preIndex,left,index-1);root.right=buildTreeRecur(inorder,preorder,preIndex,index+1,right);returnroot;}// Function to construct tree from its inorder and preorder traversalsfunctionbuildTree(inorder,preorder){constpreIndex=[0];returnbuildTreeRecur(inorder,preorder,preIndex,0,preorder.length-1);}//Driver Code Starts// Driver Codeconstinorder=[3,1,4,0,5,2];constpreorder=[0,1,3,4,2,5];constroot=buildTree(inorder,preorder);printLevelOrder(root);//Driver Code Ends
Output
0 1 2 3 4 5
[Expected Approach] Using Pre-order traversal and Hash map - O(n) Time and O(n) Space
The idea is similar to first approach, but instead of linearly searching the in-order array for each node we can use hashing. Map the values of in-order array to its indices. This will reduce the searching complexity from O(n) to O(1).
Below is the implementation of the above approach:
C++
//Driver Code Starts// c++ program to construct tree using // inorder and preorder traversals#include<iostream>#include<queue>#include<vector>#include<unordered_map>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Print tree as level ordervoidprintLevelOrder(Node*root){if(root==nullptr){cout<<"N ";return;}queue<Node*>qq;qq.push(root);intnonNull=1;while(!qq.empty()&&nonNull>0){Node*curr=qq.front();qq.pop();if(curr==nullptr){cout<<"N ";continue;}nonNull--;cout<<(curr->data)<<" ";qq.push(curr->left);qq.push(curr->right);if(curr->left)nonNull++;if(curr->right)nonNull++;}}//Driver Code Ends// Recursive function to build the binary tree.Node*buildTreeRecur(unordered_map<int,int>&mp,vector<int>&preorder,int&preIndex,intleft,intright){// For empty inorder array, return nullif(left>right)returnnullptr;introotVal=preorder[preIndex];preIndex++;// create the root NodeNode*root=newNode(rootVal);// find the index of Root element in the in-order array.intindex=mp[rootVal];// Recursively create the left and right subtree.root->left=buildTreeRecur(mp,preorder,preIndex,left,index-1);root->right=buildTreeRecur(mp,preorder,preIndex,index+1,right);returnroot;}// Function to construct tree from its inorder and preorder traversalsNode*buildTree(vector<int>&inorder,vector<int>&preorder){// Hash map that stores index of a root element in inorder arrayunordered_map<int,int>mp;for(inti=0;i<inorder.size();i++)mp[inorder[i]]=i;intpreIndex=0;Node*root=buildTreeRecur(mp,preorder,preIndex,0,inorder.size()-1);returnroot;}//Driver Code Startsintmain(){vector<int>inorder={3,1,4,0,5,2};vector<int>preorder={0,1,3,4,2,5};Node*root=buildTree(inorder,preorder);printLevelOrder(root);return0;}//Driver Code Ends
Java
//Driver Code Starts// Java program to construct tree using // inorder and preorder traversalsimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Print tree as level orderstaticvoidprintLevelOrder(Noderoot){if(root==null){System.out.print("N ");return;}Queue<Node>qq=newLinkedList<>();qq.add(root);intnonNull=1;while(!qq.isEmpty()&&nonNull>0){Nodecurr=qq.poll();if(curr==null){System.out.print("N ");continue;}nonNull--;System.out.print(curr.data+" ");qq.add(curr.left);qq.add(curr.right);if(curr.left!=null)nonNull++;if(curr.right!=null)nonNull++;}}//Driver Code Ends// Recursive function to build the binary tree.staticNodebuildTreeRecur(Map<Integer,Integer>mp,int[]preorder,int[]preIndex,intleft,intright){// For empty inorder array, return nullif(left>right)returnnull;introotVal=preorder[preIndex[0]];preIndex[0]++;// create the root NodeNoderoot=newNode(rootVal);// find the index of Root element in the in-order array.intindex=mp.get(rootVal);// Recursively create the left and right subtree.root.left=buildTreeRecur(mp,preorder,preIndex,left,index-1);root.right=buildTreeRecur(mp,preorder,preIndex,index+1,right);returnroot;}// Function to construct tree from its inorder and preorder traversalsstaticNodebuildTree(int[]inorder,int[]preorder){// Hash map that stores index of a root element in inorder arrayMap<Integer,Integer>mp=newHashMap<>();for(inti=0;i<inorder.length;i++)mp.put(inorder[i],i);int[]preIndex={0};returnbuildTreeRecur(mp,preorder,preIndex,0,inorder.length-1);}//Driver Code Startspublicstaticvoidmain(String[]args){int[]inorder={3,1,4,0,5,2};int[]preorder={0,1,3,4,2,5};Noderoot=buildTree(inorder,preorder);printLevelOrder(root);}}//Driver Code Ends
Python
#Driver Code Starts# Python program to construct tree using # inorder and preorder traversalsfromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Print tree as level orderdefprintLevelOrder(root):ifrootisNone:print("N ",end="")returnqq=deque([root])nonNull=1whileqqandnonNull>0:curr=qq.popleft()ifcurrisNone:print("N ",end="")continuenonNull-=1print(curr.data,end=" ")qq.append(curr.left)qq.append(curr.right)ifcurr.left:nonNull+=1ifcurr.right:nonNull+=1#Driver Code Ends# Recursive function to build the binary tree.defbuildTreeRecur(mp,preorder,preIndex,left,right):# For empty inorder array, return Noneifleft>right:returnNonerootVal=preorder[preIndex[0]]preIndex[0]+=1# create the root Noderoot=Node(rootVal)# find the index of Root element in the in-order array.index=mp[rootVal]# Recursively create the left and right subtree.root.left=buildTreeRecur(mp,preorder,preIndex,left,index-1)root.right=buildTreeRecur(mp,preorder,preIndex,index+1,right)returnroot# Function to construct tree from its inorder and preorder traversalsdefbuildTree(inorder,preorder):# Hash map that stores index of a root element in inorder arraymp={value:idxforidx,valueinenumerate(inorder)}preIndex=[0]returnbuildTreeRecur(mp,preorder,preIndex,0,len(inorder)-1)#Driver Code Startsif__name__=="__main__":inorder=[3,1,4,0,5,2]preorder=[0,1,3,4,2,5]root=buildTree(inorder,preorder)printLevelOrder(root)#Driver Code Ends
C#
//Driver Code Starts// C# program to construct tree using // inorder and preorder traversalsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Print tree as level orderstaticvoidPrintLevelOrder(Noderoot){if(root==null){Console.Write("N ");return;}Queue<Node>qq=newQueue<Node>();qq.Enqueue(root);intnonNull=1;while(qq.Count>0&&nonNull>0){Nodecurr=qq.Dequeue();if(curr==null){Console.Write("N ");continue;}nonNull--;Console.Write(curr.data+" ");qq.Enqueue(curr.left);qq.Enqueue(curr.right);if(curr.left!=null)nonNull++;if(curr.right!=null)nonNull++;}}//Driver Code Ends// Recursive function to build the binary tree.staticNodeBuildTreeRecur(Dictionary<int,int>mp,int[]preorder,refintpreIndex,intleft,intright){// For empty inorder array, return nullif(left>right)returnnull;introotVal=preorder[preIndex];preIndex++;// create the root NodeNoderoot=newNode(rootVal);// find the index of Root element in the in-order array.intindex=mp[rootVal];// Recursively create the left and right subtree.root.left=BuildTreeRecur(mp,preorder,refpreIndex,left,index-1);root.right=BuildTreeRecur(mp,preorder,refpreIndex,index+1,right);returnroot;}// Function to construct tree from its inorder and preorder traversalsstaticNodeBuildTree(int[]inorder,int[]preorder){// Hash map that stores index of a root element in inorder arrayDictionary<int,int>mp=newDictionary<int,int>();for(inti=0;i<inorder.Length;i++)mp[inorder[i]]=i;intpreIndex=0;returnBuildTreeRecur(mp,preorder,refpreIndex,0,inorder.Length-1);}//Driver Code StartspublicstaticvoidMain(string[]args){int[]inorder={3,1,4,0,5,2};int[]preorder={0,1,3,4,2,5};Noderoot=BuildTree(inorder,preorder);PrintLevelOrder(root);}}//Driver Code Ends
JavaScript
//Driver Code Starts// JavaScript program to construct tree using // inorder and preorder traversalsclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Print tree as level orderfunctionprintLevelOrder(root){if(root===null){process.stdout.write("N ");return;}constqq=[];qq.push(root);letnonNull=1;while(qq.length>0&&nonNull>0){constcurr=qq.shift();if(curr===null){process.stdout.write("N ");continue;}nonNull--;process.stdout.write(curr.data+" ");qq.push(curr.left);qq.push(curr.right);if(curr.left!==null)nonNull++;if(curr.right!==null)nonNull++;}}//Driver Code Ends// Recursive function to build the binary tree.functionbuildTreeRecur(mp,preorder,preIndex,left,right){// For empty inorder array, return nullif(left>right)returnnull;constrootVal=preorder[preIndex[0]];preIndex[0]++;// create the root Nodeconstroot=newNode(rootVal);// find the index of Root element in the in-order array.constindex=mp[rootVal];// Recursively create the left and right subtree.root.left=buildTreeRecur(mp,preorder,preIndex,left,index-1);root.right=buildTreeRecur(mp,preorder,preIndex,index+1,right);returnroot;}// Function to construct tree from its inorder and preorder traversalsfunctionbuildTree(inorder,preorder){// Hash map that stores index of a root element in inorder arrayconstmp={};inorder.forEach((val,idx)=>{mp[val]=idx;});constpreIndex=[0];returnbuildTreeRecur(mp,preorder,preIndex,0,inorder.length-1);}//Driver Code Starts// Driver Codeconstinorder=[3,1,4,0,5,2];constpreorder=[0,1,3,4,2,5];constroot=buildTree(inorder,preorder);printLevelOrder(root);//Driver Code Ends
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.