Construct Binary Tree from Preorder and Postorder
Master this topic with zero to advance depth.
Construct Binary Tree from Preorder and Postorder
Rebuild tree.
Level I: Recursive with Subarray Search
Intuition
In both preorder and postorder, the first element (or last in postorder) is the root. The element after the root in preorder (preorder[1]) is the root of the left subtree. We find this element in the postorder array; all elements before it in postorder belong to the left subtree.
Thought Process
root = preorder[0].- Left Root =
preorder[1]. - Find index of
preorder[1]inpostorder(linear search). - All elements until that index in
postorderare in the left subtree.
Detailed Dry Run
| Preorder | Postorder | Left Root | Post Index | Left Size |
|---|---|---|---|---|
| [1,2,4,5,3,6,7] | [4,5,2,6,7,3,1] | 2 | 2 | 3 |
Level III: Optimal (Index-based Recursion)
Intuition
Thought Process
Instead of full array slicing or repeated index searching, we maintain global pointers/indices and use a Hash Map for lookups of the left child's position in the postorder array.
Diagram
Pre: [1, 2, 4, 5, 3, 6, 7]
Idx: 0, 1, 2, 3, 4, 5, 6
If we are at 1, next is 2.
Find 2 in Post: Index 2.
Left Subtree count = 2 - 0 + 1 = 3.Detailed Dry Run
| Pre Index | Node Val | Left Val | Post Map Idx | Action |
|---|---|---|---|---|
| 0 | 1 | 2 | 2 | Build 1, proceed to Left |
| 1 | 2 | 4 | 0 | Build 2, proceed to Left |
| 2 | 4 | - | - | Leaf 4, return |
⚠️ Common Pitfalls & Tips
Note that this construction (Pre+Post) does not uniquely define a tree if any node has only one child. The standard implementation treats the single child as the left child.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.