Construct Binary Tree from Preorder and Inorder Traversal
Master this topic with zero to advance depth.
Construct Binary Tree from Preorder and Inorder Traversal
Rebuild tree.
Level I: Recursive with Linear Search
Intuition
To reconstruct a binary tree from preorder and inorder traversals, we use the fact that the first element in preorder is always the root. We then find this root in the inorder traversal. Everything to the left of the root in inorder belongs to the left subtree, and everything to the right belongs to the right subtree.
Thought Process
root = preorder[0].- Find
rootindex ininorderby iterating (Linear Search). - Slice
inorderintoleftInorderandrightInorder. - Recursively build left and right subtrees.
Detailed Dry Run
| Preorder | Inorder | Root | Left Subtree | Right Subtree |
|---|---|---|---|---|
| [3,9,20] | [9,3,20] | 3 | [9] | [20] |
Level II: Iterative with Stack
Intuition
We can build the tree iteratively using a stack. The first element of preorder is the root. For subsequent elements, if a node is a left child, it follows its parent in preorder. If it's a right child, it follows some ancestor's left subtree completion.
Logic
- Push root to stack.
- For each next value: If
stack.top().val != inorder[inIndex], it's a left child. - Else, pop from stack until
stack.top().val != inorder[inIndex]to find the parent whose right child this value is.
Detailed Dry Run
Pre:[3,9,20], In:[9,3,20]. Push 3. 3!=9 -> 9 is 3.left. Push 9. 9==9 -> Pop 9, Pop 3. Next is 20. 20 is 3.right.
Level III: Optimal (Recursive with Hash Map)
Intuition
Thought Process
Linear search for the root in the inorder array is the primary bottleneck ( per call). We can optimize this by pre-processing the inorder array into a Hash Map that stores value -> index. This reduces the lookup time to .
Diagram
Pre: [3, 9, 20, 15, 7]
In: [9, 3, 15, 20, 7]
Map: {9:0, 3:1, 15:2, 20:3, 7:4}
Step 1: Root = 3 (Index 1 in Inorder)
Left Inorder: [0..0], Right Inorder: [2..4]Detailed Dry Run
| Call | Range (Start, End) | Root Val | Map Index |
|---|---|---|---|
| Main | (0, 4) | 3 | 1 |
| Left | (0, 0) | 9 | 0 |
| Right | (2, 4) | 20 | 3 |
⚠️ Common Pitfalls & Tips
Ensure preIndex is accessed globally or passed correctly across recursive calls. Using array slicing (like preorder[1:mid+1]) is easier but often in languages like Python due to copy overhead.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.