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

Input:
Output:
🔹 Example 2:
Input:
Output:
Constraints ⚙️
1 <= preorder.length <= 3000inorder.length == preorder.length-3000 <= preorder[i], inorder[i] <= 3000preorderandinorderconsist of unique values.Each value in
inorderalso appears inpreorder.preorderis guaranteed to be the preorder traversal of the tree.inorderis guaranteed to be the inorder traversal of the tree.
Solution 💡
To construct the binary tree:
The first value in
preorderis 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
Preorder Traversal:
The first element is the root.
Subsequent elements belong to the left or right subtree.
Inorder Traversal:
Left subtree elements come before the root.
Right subtree elements come after the root.
Recursive Construction:
Use the
preorderarray 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 🧐
What changes would you make to solve the problem if the tree was not guaranteed to have unique values?
How would the approach differ for constructing a binary search tree?
You can find the full solution here.
Last updated
Was this helpful?