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.
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.