[Naive Recursive] Searching Root in Inorder - O(n²) Time and O(n) Space
The idea is based on the properties of preorder and inorder traversals. In preorder traversal, the first element is always the root of the current subtree. By searching this root in the inorder traversal, the left and right subtrees can be identified.
Take the first element of the current preorder range as the root
Find the root's index in the inorder traversal using linear search
Recursively process the left and right subtrees
Append the root to the postorder traversal
C++
#include<bits/stdc++.h>usingnamespacestd;// Find index of a value in inorder traversalintsearch(vector<int>&in,intx){for(inti=0;i<in.size();i++){if(in[i]==x)returni;}return-1;}// Recursive function to generate postorder traversalvoidbuildPostOrder(vector<int>&in,vector<int>&pre,intinStart,intinEnd,intpreStart,vector<int>&post){// No nodes in this subtreeif(inStart>inEnd)return;// First element in preorder is the rootintroot=pre[preStart];// Find root position in inorder traversalintrootIndex=search(in,root);// Process left subtreebuildPostOrder(in,pre,inStart,rootIndex-1,preStart+1,post);// Process right subtreebuildPostOrder(in,pre,rootIndex+1,inEnd,preStart+(rootIndex-inStart)+1,post);// Add root after left and right subtreepost.push_back(root);}// Function to return postorder traversalvector<int>printPostOrder(vector<int>&in,vector<int>&pre){vector<int>post;buildPostOrder(in,pre,0,in.size()-1,0,post);returnpost;}intmain(){vector<int>in={4,2,5,1,3,6};vector<int>pre={1,2,4,5,3,6};vector<int>post=printPostOrder(in,pre);for(intx:post)cout<<x<<" ";return0;}
Java
// Java program to construct postorder from inorder and preorder traversalsimportjava.util.*;classGfG{// Find index of a value in inorder traversalstaticintsearch(List<Integer>in,intx){for(inti=0;i<in.size();i++){if(in.get(i)==x)returni;}return-1;}// Recursive function to generate postorder traversalstaticvoidbuildPostOrder(List<Integer>in,List<Integer>pre,intinStart,intinEnd,intpreStart,List<Integer>post){// No nodes in this subtreeif(inStart>inEnd)return;// First element in preorder is the rootintroot=pre.get(preStart);// Find root position in inorder traversalintrootIndex=search(in,root);// Process left subtreebuildPostOrder(in,pre,inStart,rootIndex-1,preStart+1,post);// Process right subtreebuildPostOrder(in,pre,rootIndex+1,inEnd,preStart+(rootIndex-inStart)+1,post);// Add root after left and right subtreepost.add(root);}// Function to return postorder traversalstaticList<Integer>printPostOrder(List<Integer>in,List<Integer>pre){List<Integer>post=newArrayList<>();buildPostOrder(in,pre,0,in.size()-1,0,post);returnpost;}publicstaticvoidmain(String[]args){List<Integer>in=Arrays.asList(4,2,5,1,3,6);List<Integer>pre=Arrays.asList(1,2,4,5,3,6);List<Integer>post=printPostOrder(in,pre);for(intx:post){System.out.print(x+" ");}}}
Python
# Python program to construct postorder from inorder and preorder traversals# Find index of a value in inorder traversaldefsearch(inorder,x):foriinrange(len(inorder)):ifinorder[i]==x:returnireturn-1# Recursive function to generate postorder traversaldefbuildPostOrder(inorder,preorder,inStart,inEnd,preStart,post):# No nodes in this subtreeifinStart>inEnd:return# First element in preorder is the rootroot=preorder[preStart]# Find root position in inorder traversalrootIndex=search(inorder,root)# Process left subtreebuildPostOrder(inorder,preorder,inStart,rootIndex-1,preStart+1,post)# Process right subtreeleftSize=rootIndex-inStartbuildPostOrder(inorder,preorder,rootIndex+1,inEnd,preStart+leftSize+1,post)# Add root after left and right subtreepost.append(root)# Function to return postorder traversaldefprintPostOrder(inorder,preorder):post=[]buildPostOrder(inorder,preorder,0,len(inorder)-1,0,post)returnpost# Driver codeif__name__=="__main__":inorder=[4,2,5,1,3,6]preorder=[1,2,4,5,3,6]post=printPostOrder(inorder,preorder)print(' '.join(map(str,post)))
C#
// C# program to construct postorder from inorder and preorder traversalsusingSystem;usingSystem.Collections.Generic;classGfG{// Find index of a value in inorder traversalstaticintsearch(List<int>inList,intx){for(inti=0;i<inList.Count;i++){if(inList[i]==x)returni;}return-1;}// Recursive function to generate postorder traversalstaticvoidbuildPostOrder(List<int>inList,List<int>pre,intinStart,intinEnd,intpreStart,List<int>post){// No nodes in this subtreeif(inStart>inEnd)return;// First element in preorder is the rootintroot=pre[preStart];// Find root position in inorder traversalintrootIndex=search(inList,root);// Process left subtreebuildPostOrder(inList,pre,inStart,rootIndex-1,preStart+1,post);// Process right subtreeintleftSize=rootIndex-inStart;buildPostOrder(inList,pre,rootIndex+1,inEnd,preStart+leftSize+1,post);// Add root after left and right subtreepost.Add(root);}// Function to return postorder traversalstaticList<int>printPostOrder(List<int>inList,List<int>pre){List<int>post=newList<int>();buildPostOrder(inList,pre,0,inList.Count-1,0,post);returnpost;}staticvoidMain(string[]args){List<int>inorder=newList<int>{4,2,5,1,3,6};List<int>preorder=newList<int>{1,2,4,5,3,6};List<int>post=printPostOrder(inorder,preorder);foreach(intxinpost){Console.Write(x+" ");}}}
JavaScript
// JavaScript program to construct postorder from inorder and preorder traversals// Find index of a value in inorder traversalfunctionsearch(inorder,x){for(leti=0;i<inorder.length;i++){if(inorder[i]===x)returni;}return-1;}// Recursive function to generate postorder traversalfunctionbuildPostOrder(inorder,preorder,inStart,inEnd,preStart,post){// No nodes in this subtreeif(inStart>inEnd)return;// First element in preorder is the rootletroot=preorder[preStart];// Find root position in inorder traversalletrootIndex=search(inorder,root);// Process left subtreebuildPostOrder(inorder,preorder,inStart,rootIndex-1,preStart+1,post);// Process right subtreeletleftSize=rootIndex-inStart;buildPostOrder(inorder,preorder,rootIndex+1,inEnd,preStart+leftSize+1,post);// Add root after left and right subtreepost.push(root);}// Function to return postorder traversalfunctionprintPostOrder(inorder,preorder){letpost=[];buildPostOrder(inorder,preorder,0,inorder.length-1,0,post);returnpost;}// Driver codeconstinorder=[4,2,5,1,3,6];constpreorder=[1,2,4,5,3,6];constpost=printPostOrder(inorder,preorder);console.log(post.join(' '));
Output
4 5 2 6 3 1
[Efficient Approach] Hash Map for Inorder Lookup - O(n) Time and O(n) Space
The idea is to avoid repeatedly searching for the root in the inorder traversal. A hash map is used to store the index of every node in the inorder traversal.
Store each inorder value and its index in a hash map
Maintain a preorder index pointing to the current root
For each recursive call: Take the current preorder element as the root and find its inorder position using the hash map
Recursively process the left and right subtrees
Add the root to the postorder traversal
Return the generated postorder traversal
C++
#include<bits/stdc++.h>usingnamespacestd;// Recursive function to generate postorder traversalvoidbuildPostOrder(vector<int>&in,vector<int>&pre,intinStart,intinEnd,unordered_map<int,int>&mp,int&preIndex,vector<int>&post){// No nodes in this subtreeif(inStart>inEnd)return;// Current root from preorder traversalintroot=pre[preIndex++];// Find root position in inorder traversalintinIndex=mp[root];// Build left subtreebuildPostOrder(in,pre,inStart,inIndex-1,mp,preIndex,post);// Build right subtreebuildPostOrder(in,pre,inIndex+1,inEnd,mp,preIndex,post);// Add root after left and right subtreepost.push_back(root);}// Function to return postorder traversalvector<int>printPostOrder(vector<int>&in,vector<int>&pre){intn=in.size();// Stores value -> index mapping for inorder traversalunordered_map<int,int>mp;for(inti=0;i<n;i++)mp[in[i]]=i;vector<int>post;intpreIndex=0;buildPostOrder(in,pre,0,n-1,mp,preIndex,post);returnpost;}intmain(){vector<int>in={4,2,5,1,3,6};vector<int>pre={1,2,4,5,3,6};vector<int>post=printPostOrder(in,pre);for(intx:post)cout<<x<<" ";return0;}
Java
// Java program to construct postorder from inorder and preorder traversalsimportjava.util.*;classGfG{// Recursive function to generate postorder traversalstaticvoidbuildPostOrder(List<Integer>in,List<Integer>pre,intinStart,intinEnd,Map<Integer,Integer>mp,int[]preIndex,List<Integer>post){// No nodes in this subtreeif(inStart>inEnd)return;// Current root from preorder traversalintroot=pre.get(preIndex[0]);preIndex[0]++;// Find root position in inorder traversalintinIndex=mp.get(root);// Build left subtreebuildPostOrder(in,pre,inStart,inIndex-1,mp,preIndex,post);// Build right subtreebuildPostOrder(in,pre,inIndex+1,inEnd,mp,preIndex,post);// Add root after left and right subtreepost.add(root);}// Function to return postorder traversalstaticList<Integer>printPostOrder(List<Integer>in,List<Integer>pre){intn=in.size();// Stores value -> index mapping for inorder traversalMap<Integer,Integer>mp=newHashMap<>();for(inti=0;i<n;i++)mp.put(in.get(i),i);List<Integer>post=newArrayList<>();int[]preIndex={0};buildPostOrder(in,pre,0,n-1,mp,preIndex,post);returnpost;}publicstaticvoidmain(String[]args){List<Integer>in=Arrays.asList(4,2,5,1,3,6);List<Integer>pre=Arrays.asList(1,2,4,5,3,6);List<Integer>post=printPostOrder(in,pre);for(intx:post){System.out.print(x+" ");}}}
Python
# Python program to construct postorder from inorder and preorder traversals# Recursive function to generate postorder traversaldefbuildPostOrder(inorder,preorder,inStart,inEnd,mp,preIndex,post):# No nodes in this subtreeifinStart>inEnd:return# Current root from preorder traversalroot=preorder[preIndex[0]]preIndex[0]+=1# Find root position in inorder traversalinIndex=mp[root]# Build left subtreebuildPostOrder(inorder,preorder,inStart,inIndex-1,mp,preIndex,post)# Build right subtreebuildPostOrder(inorder,preorder,inIndex+1,inEnd,mp,preIndex,post)# Add root after left and right subtreepost.append(root)# Function to return postorder traversaldefprintPostOrder(inorder,preorder):n=len(inorder)# Stores value -> index mapping for inorder traversalmp={}foriinrange(n):mp[inorder[i]]=ipost=[]preIndex=[0]buildPostOrder(inorder,preorder,0,n-1,mp,preIndex,post)returnpost# Driver codeif__name__=="__main__":inorder=[4,2,5,1,3,6]preorder=[1,2,4,5,3,6]post=printPostOrder(inorder,preorder)print(' '.join(map(str,post)))
C#
// C# program to construct postorder from inorder and preorder traversalsusingSystem;usingSystem.Collections.Generic;classGfG{// Recursive function to generate postorder traversalstaticvoidbuildPostOrder(List<int>inList,List<int>pre,intinStart,intinEnd,Dictionary<int,int>mp,refintpreIndex,List<int>post){// No nodes in this subtreeif(inStart>inEnd)return;// Current root from preorder traversalintroot=pre[preIndex];preIndex++;// Find root position in inorder traversalintinIndex=mp[root];// Build left subtreebuildPostOrder(inList,pre,inStart,inIndex-1,mp,refpreIndex,post);// Build right subtreebuildPostOrder(inList,pre,inIndex+1,inEnd,mp,refpreIndex,post);// Add root after left and right subtreepost.Add(root);}// Function to return postorder traversalstaticList<int>printPostOrder(List<int>inList,List<int>pre){intn=inList.Count;// Stores value -> index mapping for inorder traversalDictionary<int,int>mp=newDictionary<int,int>();for(inti=0;i<n;i++)mp[inList[i]]=i;List<int>post=newList<int>();intpreIndex=0;buildPostOrder(inList,pre,0,n-1,mp,refpreIndex,post);returnpost;}staticvoidMain(string[]args){List<int>inorder=newList<int>{4,2,5,1,3,6};List<int>preorder=newList<int>{1,2,4,5,3,6};List<int>post=printPostOrder(inorder,preorder);foreach(intxinpost){Console.Write(x+" ");}}}
JavaScript
// JavaScript program to construct postorder from inorder and preorder traversals// Recursive function to generate postorder traversalfunctionbuildPostOrder(inorder,preorder,inStart,inEnd,mp,preIndex,post){// No nodes in this subtreeif(inStart>inEnd)return;// Current root from preorder traversalletroot=preorder[preIndex[0]];preIndex[0]++;// Find root position in inorder traversalletinIndex=mp.get(root);// Build left subtreebuildPostOrder(inorder,preorder,inStart,inIndex-1,mp,preIndex,post);// Build right subtreebuildPostOrder(inorder,preorder,inIndex+1,inEnd,mp,preIndex,post);// Add root after left and right subtreepost.push(root);}// Function to return postorder traversalfunctionprintPostOrder(inorder,preorder){constn=inorder.length;// Stores value -> index mapping for inorder traversalletmp=newMap();for(leti=0;i<n;i++)mp.set(inorder[i],i);letpost=[];letpreIndex=[0];buildPostOrder(inorder,preorder,0,n-1,mp,preIndex,post);returnpost;}// Driver codeconstinorder=[4,2,5,1,3,6];constpreorder=[1,2,4,5,3,6];constpost=printPostOrder(inorder,preorder);console.log(post.join(' '));