Algorithm-Day48-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal-lc-105
🧩 Problem Description
Given two integer arrays preorder
and inorder
where:
preorder
is the preorder traversal of a binary treeinorder
is the inorder traversal of the same tree
Construct and return the binary tree.
💬 Example
1 | Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] |
💡 Approach: DFS + HashMap for Index Lookup
Key Observations:
- In preorder traversal, the first element is always the root.
- In inorder traversal, elements to the left of root belong to the left subtree, and elements to the right belong to the right subtree.
- We can use a HashMap to store value → index mappings in inorder array for O(1) splits.
🔢 Java Code
1 | class Solution { |
⏱ Time and Space Complexity
- Time Complexity: O(n) — each node is created once, and index lookup is O(1).
- Space Complexity: O(n) — for recursion stack and hashmap.
✍️ Summary
- This is a classic divide and conquer problem.
- Preorder gives root order, inorder gives subtree boundaries.
- Related problems:
lc-106
— Construct from Inorder and Postorderlc-889
— Construct from Preorder and Postorder