Given inorder and preorder traversals of a Binary Tree in array inorder[] and preorder[] respectively, Construct the Binary Tree and return it’s root.
Note: All values in inorder[] and preorder[] are distinct.
[Approach 1] Using Pre-order traversal - O(n2) 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++
#include<iostream>#include<queue>#include<vector>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// 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++;Node*root=newNode(rootVal);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;}intgetHeight(Node*root,inth){if(root==nullptr)returnh-1;returnmax(getHeight(root->left,h+1),getHeight(root->right,h+1));}voidlevelOrder(Node*root){queue<pair<Node*,int>>q;q.push({root,0});intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!q.empty()){autotop=q.front();q.pop();Node*node=top.first;intlvl=top.second;if(lvl>lastLevel){cout<<"\n";lastLevel=lvl;}// all levels are printedif(lvl>height)break;if(node->data!=-1)cout<<node->data<<" ";// printing null nodeelsecout<<"N ";// null node has no childrenif(node->data==-1)continue;if(node->left==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->left,lvl+1});if(node->right==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->right,lvl+1});}}intmain(){vector<int>inorder={3,1,4,0,5,2};vector<int>preorder={0,1,3,4,2,5};Node*root=buildTree(inorder,preorder);levelOrder(root);return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;importjava.util.List;importjava.util.ArrayList;// Node StructureclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGFG{// 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]++;Noderoot=newNode(rootVal);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);}staticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}staticvoidlevelOrder(Noderoot){Queue<List<Object>>queue=newLinkedList<>();queue.offer(List.of(root,0));intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!queue.isEmpty()){List<Object>top=queue.poll();Nodenode=(Node)top.get(0);intlvl=(int)top.get(1);if(lvl>lastLevel){System.out.println();lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeSystem.out.print((node.data==-1?"N":node.data)+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.left,lvl+1));if(node.right==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.right,lvl+1));}}publicstaticvoidmain(String[]args){int[]inorder={3,1,4,0,5,2};int[]preorder={0,1,3,4,2,5};Noderoot=buildTree(inorder,preorder);levelOrder(root);}}
Python
fromcollectionsimportdeque# Node StructureclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# 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]+=1root=Node(rootVal)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)defgetHeight(root,h):ifrootisNone:returnh-1returnmax(getHeight(root.left,h+1),getHeight(root.right,h+1))deflevelOrder(root):queue=deque([[root,0]])lastLevel=0# function to get the height of treeheight=getHeight(root,0)# printing the level order of treewhilequeue:node,lvl=queue.popleft()iflvl>lastLevel:print()lastLevel=lvl# all levels are printediflvl>height:break# printing null nodeprint("N"ifnode.data==-1elsenode.data,end=" ")# null node has no childrenifnode.data==-1:continueifnode.leftisNone:queue.append([Node(-1),lvl+1])else:queue.append([node.left,lvl+1])ifnode.rightisNone:queue.append([Node(-1),lvl+1])else:queue.append([node.right,lvl+1])if__name__=="__main__":inorder=[3,1,4,0,5,2]preorder=[0,1,3,4,2,5]root=buildTree(inorder,preorder)levelOrder(root)
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{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>q=newQueue<Node>();q.Enqueue(root);intnonNull=1;while(q.Count>0&&nonNull>0){Nodecurr=q.Dequeue();if(curr==null){Console.Write("N ");continue;}nonNull--;Console.Write(curr.data+" ");q.Enqueue(curr.left);q.Enqueue(curr.right);if(curr.left!=null)nonNull++;if(curr.right!=null)nonNull++;}}// 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++;Noderoot=newNode(rootVal);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);}staticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.Max(getHeight(root.left,h+1),getHeight(root.right,h+1));}staticvoidlevelOrder(Noderoot){Queue<(Node,int)>queue=newQueue<(Node,int)>();queue.Enqueue((root,0));intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(queue.Count>0){var(node,lvl)=queue.Dequeue();if(lvl>lastLevel){Console.WriteLine();lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeConsole.Write((node.data==-1?"N":node.data.ToString())+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.Enqueue((newNode(-1),lvl+1));elsequeue.Enqueue((node.left,lvl+1));if(node.right==null)queue.Enqueue((newNode(-1),lvl+1));elsequeue.Enqueue((node.right,lvl+1));}}staticvoidMain(string[]args){int[]inorder={3,1,4,0,5,2};int[]preorder={0,1,3,4,2,5};Noderoot=buildTree(inorder,preorder);levelOrder(root);}}
JavaScript
// Node StructureclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Queue nodeclassQNode{constructor(data){this.data=data;this.next=null;}}classQueue{constructor(){this.front=null;this.rear=null;}isEmpty(){returnthis.front===null;}enqueue(x){letnewNode=newQNode(x);if(this.rear===null){this.front=this.rear=newNode;return;}this.rear.next=newNode;this.rear=newNode;}dequeue(){if(this.front===null)returnnull;lettemp=this.front;this.front=this.front.next;if(this.front===null)this.rear=null;returntemp.data;}}// 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]++;constroot=newNode(rootVal);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);}functiongetHeight(root,h){if(root===null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}functionlevelOrder(root){letqueue=[];queue.push([root,0]);letlastLevel=0;// get the height of treeletheight=getHeight(root,0);// printing the level order of treewhile(queue.length>0){let[node,lvl]=queue.shift();if(lvl>lastLevel){console.log("");lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeprocess.stdout.write((node.data===-1?"N":node.data)+" ");// null node has no childrenif(node.data===-1)continue;if(node.left===null)queue.push([newNode(-1),lvl+1]);elsequeue.push([node.left,lvl+1]);if(node.right===null)queue.push([newNode(-1),lvl+1]);elsequeue.push([node.right,lvl+1]);}}// Driver Codeconstinorder=[3,1,4,0,5,2];constpreorder=[0,1,3,4,2,5];constroot=buildTree(inorder,preorder);levelOrder(root);
Output
0
1 2
3 4 5 N
[Approach 2] Using Pre-order traversal and Hash map - O(n) Time and O(n) Space
The idea is similar to first approach, but instead oflinearly searchingthe in-orderarray for each node we can use hashing. Map the values of in-order arrayto its indices. This will reduce the searching complexity from O(n) to O(1).
C++
#include<iostream>#include<queue>#include<vector>#include<unordered_map>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// 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++;Node*root=newNode(rootVal);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;}intgetHeight(Node*root,inth){if(root==nullptr)returnh-1;returnmax(getHeight(root->left,h+1),getHeight(root->right,h+1));}voidlevelOrder(Node*root){queue<pair<Node*,int>>q;q.push({root,0});intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!q.empty()){autotop=q.front();q.pop();Node*node=top.first;intlvl=top.second;if(lvl>lastLevel){cout<<"\n";lastLevel=lvl;}// all levels are printedif(lvl>height)break;if(node->data!=-1)cout<<node->data<<" ";// printing null nodeelsecout<<"N ";// null node has no childrenif(node->data==-1)continue;if(node->left==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->left,lvl+1});if(node->right==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->right,lvl+1});}}intmain(){vector<int>inorder={3,1,4,0,5,2};vector<int>preorder={0,1,3,4,2,5};Node*root=buildTree(inorder,preorder);levelOrder(root);return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;importjava.util.List;importjava.util.HashMap;importjava.util.Map;importjava.util.ArrayList;// Node StructureclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGFG{// 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]++;Noderoot=newNode(rootVal);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);}staticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}staticvoidlevelOrder(Noderoot){Queue<List<Object>>queue=newLinkedList<>();queue.offer(List.of(root,0));intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!queue.isEmpty()){List<Object>top=queue.poll();Nodenode=(Node)top.get(0);intlvl=(int)top.get(1);if(lvl>lastLevel){System.out.println();lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeSystem.out.print((node.data==-1?"N":node.data)+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.left,lvl+1));if(node.right==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.right,lvl+1));}}publicstaticvoidmain(String[]args){int[]inorder={3,1,4,0,5,2};int[]preorder={0,1,3,4,2,5};Noderoot=buildTree(inorder,preorder);levelOrder(root);}}
Python
fromcollectionsimportdeque# Node StructureclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# 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]+=1root=Node(rootVal)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)defgetHeight(root,h):ifrootisNone:returnh-1returnmax(getHeight(root.left,h+1),getHeight(root.right,h+1))deflevelOrder(root):queue=deque([[root,0]])lastLevel=0# function to get the height of treeheight=getHeight(root,0)# printing the level order of treewhilequeue:node,lvl=queue.popleft()iflvl>lastLevel:print()lastLevel=lvl# all levels are printediflvl>height:break# printing null nodeprint("N"ifnode.data==-1elsenode.data,end=" ")# null node has no childrenifnode.data==-1:continueifnode.leftisNone:queue.append([Node(-1),lvl+1])else:queue.append([node.left,lvl+1])ifnode.rightisNone:queue.append([Node(-1),lvl+1])else:queue.append([node.right,lvl+1])if__name__=="__main__":inorder=[3,1,4,0,5,2]preorder=[0,1,3,4,2,5]root=buildTree(inorder,preorder)levelOrder(root)
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGFG{// 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++;Noderoot=newNode(rootVal);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);}staticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.Max(getHeight(root.left,h+1),getHeight(root.right,h+1));}staticvoidlevelOrder(Noderoot){Queue<(Node,int)>queue=newQueue<(Node,int)>();queue.Enqueue((root,0));intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(queue.Count>0){var(node,lvl)=queue.Dequeue();if(lvl>lastLevel){Console.WriteLine();lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeConsole.Write((node.data==-1?"N":node.data.ToString())+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.Enqueue((newNode(-1),lvl+1));elsequeue.Enqueue((node.left,lvl+1));if(node.right==null)queue.Enqueue((newNode(-1),lvl+1));elsequeue.Enqueue((node.right,lvl+1));}}publicstaticvoidMain(string[]args){int[]inorder={3,1,4,0,5,2};int[]preorder={0,1,3,4,2,5};Noderoot=buildTree(inorder,preorder);levelOrder(root);}}
JavaScript
// Node StructureclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Queue nodeclassQNode{constructor(data){this.data=data;this.next=null;}}classQueue{constructor(){this.front=null;this.rear=null;}isEmpty(){returnthis.front===null;}enqueue(x){letnewNode=newQNode(x);if(this.rear===null){this.front=this.rear=newNode;return;}this.rear.next=newNode;this.rear=newNode;}dequeue(){if(this.front===null)returnnull;lettemp=this.front;this.front=this.front.next;if(this.front===null)this.rear=null;returntemp.data;}}// 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]++;constroot=newNode(rootVal);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);}functiongetHeight(root,h){if(root===null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}functionlevelOrder(root){letqueue=[];queue.push([root,0]);letlastLevel=0;// get the height of treeletheight=getHeight(root,0);// printing the level order of treewhile(queue.length>0){let[node,lvl]=queue.shift();if(lvl>lastLevel){console.log("");lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeprocess.stdout.write((node.data===-1?"N":node.data)+" ");// null node has no childrenif(node.data===-1)continue;if(node.left===null)queue.push([newNode(-1),lvl+1]);elsequeue.push([node.left,lvl+1]);if(node.right===null)queue.push([newNode(-1),lvl+1]);elsequeue.push([node.right,lvl+1]);}}// Driver Codeconstinorder=[3,1,4,0,5,2];constpreorder=[0,1,3,4,2,5];constroot=buildTree(inorder,preorder);levelOrder(root);