Imagine you're given two different blueprints of the same binary tree - one showing the order in which nodes were visited in a preorder traversal (root → left → right), and another showing the order from an inorder traversal (left → root → right).
Your task is to reconstruct the original binary tree using these two traversal sequences. This is like being an architect who needs to rebuild a building from two different perspective drawings!
Key insight: The preorder array tells us which node is the root at each step, while the inorder array tells us which nodes belong to the left vs right subtrees.
Example:preorder = [3,9,20,15,7]inorder = [9,3,15,20,7]
From this, we can deduce that 3 is the root (first in preorder), 9 is the left subtree (everything left of 3 in inorder), and [20,15,7] forms the right subtree.
Input & Output
Visualization
Time & Space Complexity
O(n) to build hash map + O(n) for tree construction with O(1) lookups
O(n) for hash map + O(n) for recursion stack in worst case
Constraints
- 1 ≤ preorder.length ≤ 3000
- inorder.length == preorder.length
- -3000 ≤ preorder[i], inorder[i] ≤ 3000
- preorder and inorder consist of unique values
- inorder is guaranteed to be the inorder traversal of the same tree that preorder is the preorder traversal of