Construct a Binary Tree from Postorder and Inorder
Last Updated : 23 Jul, 2025
Given inorder and postorder traversals of a binary tree(having n nodes) in the arrays inorder[] and postorder[] respectively. The task is to construct a unique binary tree from these traversals and return the preorder traversal of the constructed tree.
Examples:
Input: inorder[] = [2, 1, 3], postorder[] = [2, 3, 1] Output: 1 2 3 Explanation: The below tree is constructed from the given inorder and postorder traversal.
Input: inorder[] = [4, 2, 5, 1, 3], postorder[] = [4, 5, 2, 3, 1] Output: 1 2 4 5 3 Explanation: The below tree is constructed from the given inorder and postorder traversal.
[Naive approach] Search current element every time - O(n^2) Time and O(n) Space
The idea behind this algorithm is to construct a binary tree using the given inorder and postorder traversals. We start by recognizing that the last element of the postorder traversal represents the root of the tree. Using this value, we find its position in the inorder traversal, which allows us to divide the tree into left and right subtrees. We then recursively repeat this process, constructing the right subtree first and then the left subtree. Once the tree is fully constructed, we can perform a preorder traversal to print the elements in the desired order.
Note: One important observation is, that we recursively call for the right subtree before the left subtree as we decrease the index of the postorder index whenever we create a new node.
C++
// C++ program to construct tree using inorder and// postorder traversals#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Function to find index of value in arr[start...end]// The function assumes that value is present in in[]intsearch(vector<int>&arr,intstrt,intend,intvalue){inti;for(i=strt;i<=end;i++){if(arr[i]==value)break;}returni;}// Recursive function to construct binary tree of size n// from Inorder traversal in[] and Postorder traversal// post[]. Initial values of inStrt and inEnd should// be 0 and n - 1.Node*buildUtil(vector<int>&inorder,vector<int>&postorder,intinStrt,intinEnd,int&pIndex){// if inStart is greater than inEnd return nullptrif(inStrt>inEnd)returnnullptr;// Pick current node from Postorder traversal using// postIndex and decrement postIndexNode*node=newNode(postorder[pIndex]);pIndex--;// If this node has no children then returnif(inStrt==inEnd)returnnode;// Else find the index of this node in Inorder traversalintiIndex=search(inorder,inStrt,inEnd,node->data);// Using index in Inorder traversal, construct left and// right subtreesnode->right=buildUtil(inorder,postorder,iIndex+1,inEnd,pIndex);node->left=buildUtil(inorder,postorder,inStrt,iIndex-1,pIndex);returnnode;}// This function mainly initializes index of root// and calls buildUtil()Node*buildTree(vector<int>&inorder,vector<int>&postorder){intn=inorder.size();intpIndex=n-1;returnbuildUtil(inorder,postorder,0,n-1,pIndex);}// Print the preorder traversal of a binary treevoidprint(Node*curr){if(curr==nullptr)return;cout<<curr->data<<" ";print(curr->left);print(curr->right);}intmain(){vector<int>inorder={4,8,2,5,1,6,3,7};vector<int>postorder={8,4,5,2,6,7,3,1};Node*root=buildTree(inorder,postorder);print(root);return0;}
C
// C program to construct tree using// inorder and postorder traversals#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};structNode*createNode(intx);// Function to find index of value in arr[start...end]// The function assumes that value is present in in[]intsearch(intarr[],intstart,intend,intvalue){inti;for(i=start;i<=end;i++){if(arr[i]==value)break;}returni;}// Recursive function to construct binary tree of size n// from Inorder traversal in[] and Postorder traversal// post[].structNode*buildUtil(intinorder[],intpostorder[],intinStart,intinEnd,int*pIndex){if(inStart>inEnd)returnNULL;// Pick current node from Postorder traversal using// postIndex and decrement postIndexstructNode*node=createNode(postorder[*pIndex]);(*pIndex)--;// If this node has no children then returnif(inStart==inEnd)returnnode;// Else find the index of this node in Inorder traversalintinIndex=search(inorder,inStart,inEnd,node->data);// Using index in Inorder traversal, construct left and// right subtreesnode->right=buildUtil(inorder,postorder,inIndex+1,inEnd,pIndex);node->left=buildUtil(inorder,postorder,inStart,inIndex-1,pIndex);returnnode;}// This function mainly initializes index of root// and calls buildUtil()structNode*buildTree(intinorder[],intpostorder[],intn){intpIndex=n-1;returnbuildUtil(inorder,postorder,0,n-1,&pIndex);}// Print the preorder of a binary treevoidprintPreorder(structNode*node){if(node==NULL)return;printf("%d ",node->data);printPreorder(node->left);printPreorder(node->right);}structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->left=NULL;node->right=NULL;returnnode;}intmain(){intinorder[]={4,8,2,5,1,6,3,7};intpostorder[]={8,4,5,2,6,7,3,1};intn=sizeof(inorder)/sizeof(inorder[0]);structNode*root=buildTree(inorder,postorder,n);printPreorder(root);return0;}
Java
// Java program to construct tree using// inorder and postorder traversalsimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to find index of value in arr[start...end]// The function assumes that value is present in in[]staticintsearch(List<Integer>arr,intstrt,intend,intvalue){inti;for(i=strt;i<=end;i++){if(arr.get(i)==value)break;}returni;}// Recursive function to construct binary of size n// from Inorder traversal in[] and Postorder traversal// post[]. Initial values of inStrt and inEnd should// be 0 and n -1.staticNodebuildUtil(List<Integer>in,List<Integer>post,intinStrt,intinEnd,int[]pIndex){if(inStrt>inEnd)returnnull;// Pick current node from Postorder traversal using// postIndex and decrement postIndexNodenode=newNode(post.get(pIndex[0]));pIndex[0]--;// If this node has no children then returnif(inStrt==inEnd)returnnode;// Else find the index of this node in Inorder// traversalintiIndex=search(in,inStrt,inEnd,node.data);// Using index in Inorder traversal, construct left// and right subtreesnode.right=buildUtil(in,post,iIndex+1,inEnd,pIndex);node.left=buildUtil(in,post,inStrt,iIndex-1,pIndex);returnnode;}// This function mainly initializes index of root// and calls buildUtil()staticNodebuildTree(List<Integer>in,List<Integer>post){intn=in.size();int[]pIndex={n-1};returnbuildUtil(in,post,0,n-1,pIndex);}// Print the preorder of a binary treestaticvoidprint(Nodecurr){if(curr==null)return;System.out.print(curr.data+" ");print(curr.left);print(curr.right);}publicstaticvoidmain(String[]args){List<Integer>in=Arrays.asList(4,8,2,5,1,6,3,7);List<Integer>post=Arrays.asList(8,4,5,2,6,7,3,1);Noderoot=buildTree(in,post);print(root);}}
Python
# Python program to construct tree using # inorder and postorder traversalsclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to find index of value in arr[start...end]# The function assumes that value is present in in[]defsearch(arr,start,end,value):foriinrange(start,end+1):ifarr[i]==value:returnireturn-1# Recursive function to construct binary tree of size n# from Inorder traversal in[] and Postorder traversal# post[]. Initial values of inStrt and inEnd should# be 0 and n - 1.defbuild_util(inorder,postorder,in_start,in_end,post_index):ifin_start>in_end:returnNone# Pick current node from Postorder traversal using# postIndex and decrement postIndexnode=Node(postorder[post_index[0]])post_index[0]-=1# If this node has no children then returnifin_start==in_end:returnnode# Else find the index of this node in Inorder traversalin_index=search(inorder,in_start,in_end,node.data)# Using index in Inorder traversal, construct left and# right subtreesnode.right=build_util(inorder,postorder,in_index+1,in_end,post_index)node.left=build_util(inorder,postorder,in_start,in_index-1,post_index)returnnode# This function mainly initializes index of root# and calls buildUtil()defbuildTree(inorder,postorder):n=len(inorder)post_index=[n-1]returnbuild_util(inorder,postorder,0,n-1,post_index)# Print the preorder of a binary treedefprint_preorder(node):ifnodeisNone:returnprint(node.data,end=" ")print_preorder(node.left)print_preorder(node.right)if__name__=="__main__":inorder=[4,8,2,5,1,6,3,7]postorder=[8,4,5,2,6,7,3,1]root=buildTree(inorder,postorder)print_preorder(root)
C#
// C# program to construct tree using// inorder and postorder traversalsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to find index of value in arr[start...end]// The function assumes that value is present in in[]staticintSearch(List<int>arr,intstart,intend,intvalue){inti;for(i=start;i<=end;i++){if(arr[i]==value)break;}returni;}// Recursive function to construct binary of size n// from Inorder traversal in[] and Postorder traversal// post[]. Initial values of inStrt and inEnd should// be 0 and n -1.staticNodeBuildUtil(List<int>inorder,List<int>postorder,intinStart,intinEnd,refintpIndex){if(inStart>inEnd)returnnull;// Pick current node from Postorder traversal using// postIndex and decrement postIndexNodenode=newNode(postorder[pIndex]);pIndex--;// If this node has no children then returnif(inStart==inEnd)returnnode;// Else find the index of this node in Inorder traversalintinIndex=Search(inorder,inStart,inEnd,node.data);// Using index in Inorder traversal, construct left and// right subtreesnode.right=BuildUtil(inorder,postorder,inIndex+1,inEnd,refpIndex);node.left=BuildUtil(inorder,postorder,inStart,inIndex-1,refpIndex);returnnode;}// This function mainly initializes index of root// and calls BuildUtil()staticNodebuildTree(List<int>inorder,List<int>postorder){intn=inorder.Count;intpIndex=n-1;returnBuildUtil(inorder,postorder,0,n-1,refpIndex);}// Print the preorder of a binary treestaticvoidPrint(Nodecurr){if(curr==null)return;Console.Write(curr.data+" ");Print(curr.left);Print(curr.right);}staticvoidMain(){List<int>inorder=newList<int>{4,8,2,5,1,6,3,7};List<int>postorder=newList<int>{8,4,5,2,6,7,3,1};Noderoot=buildTree(inorder,postorder);Print(root);}}
JavaScript
// JavaScript program to construct tree using// inorder and postorder traversalsclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to find index of value in arr[start...end]// The function assumes that value is present in in[]functionsearch(arr,start,end,value){for(leti=start;i<=end;i++){if(arr[i]===value)returni;}return-1;}// Recursive function to construct binary of size n// from Inorder traversal in[] and Postorder traversal// post[]. Initial values of inStrt and inEnd should// be 0 and n -1.functionbuildUtil(inorder,postorder,inStart,inEnd,postIndex){if(inStart>inEnd){returnnull;}// Pick current node from Postorder traversal using// postIndex and decrement postIndexconstnode=newNode(postorder[postIndex[0]]);postIndex[0]--;// If this node has no children then returnif(inStart===inEnd){returnnode;}// Else find the index of this node in Inorder traversalconstinIndex=search(inorder,inStart,inEnd,node.data);// Using index in Inorder traversal, construct left and// right subtreesnode.right=buildUtil(inorder,postorder,inIndex+1,inEnd,postIndex);node.left=buildUtil(inorder,postorder,inStart,inIndex-1,postIndex);returnnode;}// This function mainly initializes index of root// and calls buildUtil()functionbuildTree(inorder,postorder){constn=inorder.length;letpostIndex=[n-1];returnbuildUtil(inorder,postorder,0,n-1,postIndex);}// Print the preorder of a binary treefunctionprintPreorder(node){if(node===null){return;}console.log(node.data+" ");printPreorder(node.left);printPreorder(node.right);}constinorder=[4,8,2,5,1,6,3,7];constpostorder=[8,4,5,2,6,7,3,1];constroot=buildTree(inorder,postorder);printPreorder(root);
Output
1 2 4 8 5 3 6 7
[Expected Approach] Using hashing - O(n) Time and O(n) Space
The idea is to optimize the above solution using hashing. We store indexes of inorder traversal in a hash table. So that search can be done O(1) time, if given that element in the tree is not repeated.
Follow the below steps to solve the problem:
We first find the last node in postorder[]. The last node is lets say x, we know this value is the root as the root always appears at the end of postorder traversal.
We get the index of postorder[i], in inorder using the map to find the left and right subtrees of the root. Everything on the left of x in inorder[] is in the left subtree and everything on right is in the right subtree.
We recur the above process for the following two.
Recur for right side in inorder[] and decrease index of postorder index .Make the created tree as right child of root.
Recur for left side in inorder[] and decrease index of postorder index .Make the created tree as left child of root.
C++
// C++ program to construct a binary tree // using inorder and postorder traversals#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to recursively build the tree from// inorder and postorder traversalsNode*buildUtil(vector<int>&inorder,vector<int>&postorder,intinStrt,intinEnd,int&pIndex,unordered_map<int,int>&mp){// if start index exceeds end index, return NULLif(inStrt>inEnd)returnNULL;// Get the current node value from postorder // traversal using pIndex and decrement pIndexintcurr=postorder[pIndex];Node*node=newNode(curr);pIndex--;// If the current node has no children // (inStrt == inEnd), return the nodeif(inStrt==inEnd)returnnode;// Find the index of the current node's// value in the inorder traversalintiIndex=mp[curr];// Recursively build the right and left subtreesnode->right=buildUtil(inorder,postorder,iIndex+1,inEnd,pIndex,mp);node->left=buildUtil(inorder,postorder,inStrt,iIndex-1,pIndex,mp);returnnode;}// Main function to build the binary tree // from inorder and postorder vectorsNode*buildTree(vector<int>&inorder,vector<int>&postorder){intlen=inorder.size();// Create an unordered map to store the // indexes of inorder elements for quick lookupunordered_map<int,int>mp;for(inti=0;i<len;i++)mp[inorder[i]]=i;// Initialize postorder index as the last elementintpostIndex=len-1;// Call the recursive utility function to build the treereturnbuildUtil(inorder,postorder,0,len-1,postIndex,mp);}voidprint(Node*curr){if(curr==nullptr)return;cout<<curr->data<<" ";print(curr->left);print(curr->right);}intmain(){vector<int>inorder={4,8,2,5,1,6,3,7};vector<int>postorder={8,4,5,2,6,7,3,1};Node*root=buildTree(inorder,postorder);print(root);return0;}
Java
// Java program to construct a binary tree // using inorder and postorder traversalsimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to recursively build the tree from// inorder and postorder traversalsstaticNodebuildUtil(List<Integer>inorder,List<Integer>postorder,intinStrt,intinEnd,int[]pIndex,Map<Integer,Integer>mp){// if start index exceeds end index, return nullif(inStrt>inEnd)returnnull;// Get the current node value from postorder// traversal using pIndex and decrement pIndexintcurr=postorder.get(pIndex[0]);Nodenode=newNode(curr);pIndex[0]--;// If the current node has no children// (inStrt == inEnd), return the nodeif(inStrt==inEnd)returnnode;// Find the index of the current node's// value in the inorder traversalintiIndex=mp.get(curr);// Recursively build the right and left subtreesnode.right=buildUtil(inorder,postorder,iIndex+1,inEnd,pIndex,mp);node.left=buildUtil(inorder,postorder,inStrt,iIndex-1,pIndex,mp);returnnode;}// Main function to build the binary tree// from inorder and postorder vectorsstaticNodebuildTree(List<Integer>inorder,List<Integer>postorder){intlen=inorder.size();// Create an unordered map to store the// indexes of inorder elements for quick lookupMap<Integer,Integer>mp=newHashMap<>();for(inti=0;i<len;i++)mp.put(inorder.get(i),i);// Initialize postorder index as the last elementint[]postIndex=newint[]{len-1};// Call the recursive utility function to build the treereturnbuildUtil(inorder,postorder,0,len-1,postIndex,mp);}// Function to print preorder traversal of the treestaticvoidprint(Nodecurr){if(curr==null)return;System.out.print(curr.data+" ");print(curr.left);print(curr.right);}publicstaticvoidmain(String[]args){List<Integer>inorder=Arrays.asList(4,8,2,5,1,6,3,7);List<Integer>postorder=Arrays.asList(8,4,5,2,6,7,3,1);Noderoot=buildTree(inorder,postorder);print(root);}}
Python
# Python program to construct a binary tree # using inorder and postorder traversalsclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to recursively build the tree from# inorder and postorder traversalsdefbuildUtil(inorder,postorder,inStrt,inEnd,pIndex,mp):# if start index exceeds end index, return NoneifinStrt>inEnd:returnNone# Get the current node value from postorder# traversal using pIndex and decrement pIndexcurr=postorder[pIndex[0]]node=Node(curr)pIndex[0]-=1# If the current node has no children# (inStrt == inEnd), return the nodeifinStrt==inEnd:returnnode# Find the index of the current node's# value in the inorder traversaliIndex=mp[curr]# Recursively build the right and left subtreesnode.right=buildUtil(inorder,postorder,iIndex+1,inEnd,pIndex,mp)node.left=buildUtil(inorder,postorder,inStrt,iIndex-1,pIndex,mp)returnnode# Main function to build the binary tree# from inorder and postorder vectorsdefbuildTree(inorder,postorder):# Create a dictionary to store the# indexes of inorder elements for quick lookupmp={val:idxforidx,valinenumerate(inorder)}# Initialize postorder index as the last elementpIndex=[len(postorder)-1]# Call the recursive utility function to build the treereturnbuildUtil(inorder,postorder,0,len(inorder)-1,pIndex,mp)# Function to print preorder traversal of the treedefprintTree(curr):ifcurrisNone:returnprint(curr.data,end=" ")printTree(curr.left)printTree(curr.right)if__name__=="__main__":inorder=[4,8,2,5,1,6,3,7]postorder=[8,4,5,2,6,7,3,1]root=buildTree(inorder,postorder)printTree(root)
C#
// C# program to construct a binary tree // using inorder and postorder traversalsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to recursively build the tree from// inorder and postorder traversalsstaticNodeBuildUtil(List<int>inorder,List<int>postorder,intinStrt,intinEnd,refintpIndex,Dictionary<int,int>mp){// if start index exceeds end index, return nullif(inStrt>inEnd)returnnull;// Get the current node value from postorder// traversal using pIndex and decrement pIndexintcurr=postorder[pIndex];Nodenode=newNode(curr);pIndex--;// If the current node has no children// (inStrt == inEnd), return the nodeif(inStrt==inEnd)returnnode;// Find the index of the current node's// value in the inorder traversalintiIndex=mp[curr];// Recursively build the right and left subtreesnode.right=BuildUtil(inorder,postorder,iIndex+1,inEnd,refpIndex,mp);node.left=BuildUtil(inorder,postorder,inStrt,iIndex-1,refpIndex,mp);returnnode;}// Main function to build the binary tree// from inorder and postorder vectorsstaticNodebuildTree(List<int>inorder,List<int>postorder){// Create a dictionary to store the// indexes of inorder elements for quick lookupDictionary<int,int>mp=newDictionary<int,int>();for(inti=0;i<inorder.Count;i++)mp[inorder[i]]=i;// Initialize postorder index as the last elementintpostIndex=postorder.Count-1;// Call the recursive utility function// to build the treereturnBuildUtil(inorder,postorder,0,inorder.Count-1,refpostIndex,mp);}// Function to print preorder traversal of the treestaticvoidPrint(Nodecurr){if(curr==null)return;Console.Write(curr.data+" ");Print(curr.left);Print(curr.right);}staticvoidMain(string[]args){List<int>inorder=newList<int>{4,8,2,5,1,6,3,7};List<int>postorder=newList<int>{8,4,5,2,6,7,3,1};Noderoot=buildTree(inorder,postorder);Print(root);}}
JavaScript
// JavaScript program to construct a binary tree // using inorder and postorder traversalsclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to recursively build the tree from// inorder and postorder traversalsfunctionbuildUtil(inorder,postorder,inStrt,inEnd,pIndex,mp){// If start index exceeds end index, return nullif(inStrt>inEnd){returnnull;}// Get the current node value from postorder // traversal using pIndex and decrement pIndexconstcurr=postorder[pIndex[0]];constnode=newNode(curr);pIndex[0]--;// If the current node has no children // (inStrt == inEnd), return the nodeif(inStrt===inEnd){returnnode;}// Find the index of the current node's// value in the inorder traversalconstiIndex=mp[curr];// Recursively build the right and left subtreesnode.right=buildUtil(inorder,postorder,iIndex+1,inEnd,pIndex,mp);node.left=buildUtil(inorder,postorder,inStrt,iIndex-1,pIndex,mp);returnnode;}functionbuildTree(inorder,postorder){constlen=inorder.length;constmp={};for(leti=0;i<len;i++){mp[inorder[i]]=i;}// Initialize postorder index as the last elementconstpostIndex=[len-1];// Call the recursive utility function to build the treereturnbuildUtil(inorder,postorder,0,len-1,postIndex,mp);}// Function to print the binary tree in preorderfunctionprint(curr){if(curr===null){return;}console.log(curr.data+" ");print(curr.left);print(curr.right);}// Inorder and postorder traversals // of the binary treeconstinorder=[4,8,2,5,1,6,3,7];constpostorder=[8,4,5,2,6,7,3,1];constroot=buildTree(inorder,postorder);print(root);