Construct Binary Tree from Inorder and Postorder Traversal
MediumTop Interview 150 TreesProblem
You are given two arrays that describe the same binary tree: inorder, where the left subtree comes
first, then the node, then the right subtree, and postorder, where both subtrees come before their node
(left, right, root). All values are distinct.
Rebuild the tree and return its root. Trees are written in level order, with null for a missing child.
Constraints
- 1 ≤ n ≤ 3000
- inorder and postorder both hold the same n distinct values
- -3000 ≤ value ≤ 3000
Examples: pick one to animate
Solutions
Time: The map is built in one pass, and then each of the n nodes is created once, with a constant-time lookup to find its root.
Space: The map holds n entries, and the recursion goes as deep as the tree is tall, up to n for a chain.
The last value of any postorder part is that subtree's root. Find the root in inorder: everything before it is the left subtree and everything after it is the right subtree. Reading postorder backwards gives root, then right subtree, then left subtree, so build the right side first. The right size tells where the left part ends. A map from value to inorder index makes each lookup instant.