106. Construct Binary Tree from Inorder and Postorder Traversal 🔗
Difficulty: Medium - Tags: Binary Tree, Divide and Conquer, Recursion
Problem Statement 📜
Given two integer arrays inorder and postorder:
inorderrepresents the inorder traversal of a binary tree.postorderrepresents the postorder traversal of the same binary tree.
Construct and return the binary tree.
Examples 🌟
🔹 Example 1:

Input:
Output:
🔹 Example 2:
Input:
Output:
Constraints ⚙️
1 <= inorder.length <= 3000postorder.length == inorder.length-3000 <= inorder[i], postorder[i] <= 3000inorderandpostorderconsist of unique values.Each value of
postorderalso appears ininorder.inorderis guaranteed to be the inorder traversal of the tree.postorderis guaranteed to be the postorder traversal of the tree.
Solution 💡
To construct the binary tree:
The last value in
postorderis the root node.Find the root node's position in
inorder. Values to the left belong to the left subtree, and values to the right belong to the right subtree.Recursively repeat this process for the left and right subtrees.
Java Solution
Explanation of the Solution
Postorder Traversal:
The last element is the root.
The second-to-last element is part of the right subtree.
Inorder Traversal:
Left subtree elements come before the root.
Right subtree elements come after the root.
Recursive Construction:
Use the
postorderarray to pick the root.Divide the
inorderarray into left and right subtrees.Recursively construct the tree for both subtrees.
Time Complexity ⏳
O(n), where
nis the number of nodes. Each node is visited once, and theHashMapprovidesO(1)lookups for the index.
Space Complexity 💾
O(n) for the
HashMapand recursive stack space.
Follow-up Challenges 🧐
Could you modify the solution if the tree had duplicate values?
What if the input arrays were very large? How would you optimize memory usage?
You can find the full solution here.
Last updated
Was this helpful?