Given two integer arrays inorder and postorder representing the inorder traversal and postorder traversal of the same binary tree, your task is to reconstruct and return the original binary tree.
In an inorder traversal, we visit nodes in the pattern: Left → Root → Right
In a postorder traversal, we visit nodes in the pattern: Left → Right → Root
This is a classic tree reconstruction problem that tests your understanding of tree traversal properties and recursive thinking. The key insight is that the last element in postorder is always the root, and we can use the inorder array to determine which elements belong to the left and right subtrees.
Example: If inorder = [9,3,15,20,7] and postorder = [9,15,7,20,3], the tree looks like:
3
/ \
9 20
/ \
15 7 Input & Output
Visualization
Time & Space Complexity
We visit each node exactly once, and hash map lookups are O(1)
Hash map stores n entries, plus O(n) recursion stack depth
Constraints
- 1 ≤ inorder.length ≤ 3000
- postorder.length == inorder.length
- -3000 ≤ inorder[i], postorder[i] ≤ 3000
- inorder and postorder consist of unique values
- Each value of postorder also appears in inorder
- inorder is guaranteed to be the inorder traversal of the tree
- postorder is guaranteed to be the postorder traversal of the same tree