Problem 106 · LeetCode 106(opens in a new tab)
Construct Binary Tree from Inorder and Postorder Traversal
MediumHash tables
A binary tree with all-different values was walked twice. inorder lists its values in inorder (left subtree, node, right subtree). postorder lists them in postorder (left subtree, right subtree, node).
Rebuild the tree from the two lists and return its root. Both lists come from the same tree, so exactly one tree fits.
Example 1
Input: inorder = [1, 2, 4, 5, 8, 9], postorder = [1, 4, 2, 9, 8, 5] Output: [5, 2, 8, 1, 4, null, 9] Why: 5 is last in postorder, so it is the root
2 more examples and the constraints
Example 2
Input: inorder = [-7], postorder = [-7] Output: [-7] Why: one value makes a one-node tree
Example 3
Input: inorder = [1, 2, 3], postorder = [3, 2, 1] Output: [1, null, 2, null, 3] Why: nothing sits left of 1 in inorder
Constraints
- 1 ≤ number of nodes ≤ 3,000
inorderandpostorderhave the same length- Each value is between −3,000 and 3,000, and all values are different
- Both lists are valid traversals of the same tree
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion, scanning for the rootO(n²)
- Recursion with a position mapO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 3,000 nodes in a chain | Verdict |
|---|---|---|---|
| Recursion, scanning for the root | O(n²) | Passes here, but wasteful | |
| Recursion with a position map | O(n) | Best; one lookup per node |
n = number of nodes. On a balanced tree the scan costs only O(n log n); a chain is its worst case.
Edge cases to test
- One node. [-7] and [-7] give a single node.
- Only left children. Then both lists are the same, e.g. [1, 2, 3] twice gives [3, 2, null, 1].
- Only right children. inorder [1, 2, 3], postorder [3, 2, 1] gives [1, null, 2, null, 3].
- A deep chain. 3,000 nodes in a line means 3,000 nested calls; raise Python’s recursion limit.
Common mistakes
- Building the left subtree first, so the postorder pointer hands out roots from the right subtree.
- Slicing new arrays for every call, which costs O(n) per call and O(n²) memory traffic.
- Taking the root from the front of postorder, as you would with preorder.
How to talk through it
- 1Clarify. Are the values unique? Are both lists always valid for the same tree?
- 2Find the root. The last postorder value is the root; its inorder position splits left from right.
- 3Give the scan version. Recurse on both sides and say the linear search makes it O(n²) on a chain.
- 4Add the map. Map value to inorder index, keep one pointer into postorder, and build right before left.
- 5Test out loud. Run one node, a left chain and a right chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?