LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal is a Medium binary tree general problem. This Python walkthrough develops a reverse postorder partition solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Binary Tree General |
| Reusable pattern | reverse postorder partition |
| Complexity | O(n) time and O(n) space |
Recognizing the pattern
Tree recursion works when the return value has one precise meaning for every subtree; the parent can then combine child results locally.
For this problem specifically, take roots from postorder backward and build the right subtree before the left using inorder boundaries. The invariant worth writing beside the code is: The reverse postorder cursor identifies the root of the current inorder range, followed by its right subtree.
Step-by-step algorithm
- Identify the input state consumed by
buildTree(inorder, postorder)and initialize the data required by the reverse postorder partition pattern. - Take roots from postorder backward and build the right subtree before the left using inorder boundaries.
- After each update, verify the page’s central invariant: The reverse postorder cursor identifies the root of the current inorder range, followed by its right subtree.
- Finish only after the boundary behavior is covered: Building left first would consume roots in the wrong order.
Python solution
LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.
class Solution:
def buildTree(self, inorder, postorder):
position = {value: i for i, value in enumerate(inorder)}
post_index = len(postorder) - 1
def build(left, right):
nonlocal post_index
if left > right:
return None
value = postorder[post_index]
post_index -= 1
root = TreeNode(value)
split = position[value]
root.right = build(split + 1, right)
root.left = build(left, split - 1)
return root
return build(0, len(inorder) - 1)Reading the implementation
The main entry point is buildTree(inorder, postorder). The named working state includes position, post_index, value, root, split; those variables make the reverse postorder partition state visible instead of hiding it in incidental control flow.
The method expresses the transformation directly without a general traversal loop. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, take roots from postorder backward and build the right subtree before the left using inorder boundaries.
Correctness argument
Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.
Inductive step. Take roots from postorder backward and build the right subtree before the left using inorder boundaries. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so the reverse postorder cursor identifies the root of the current inorder range, followed by its right subtree.
Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.
Complexity and trade-offs
O(n) time and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
An explicit stack avoids recursion-depth limits, but it must carry the same state that recursive call frames provide automatically. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
built=Solution().buildTree([9,3,15,20,7],[9,15,7,20,3]); assert inorder(built)==[9,3,15,20,7]Common mistakes and edge cases
- Problem-specific boundary: Building left first would consume roots in the wrong order.
- Pattern-level pitfall: Write the empty-subtree result first and keep returned subtree information separate from any global answer updated at a node.
- Invariant check: after every update, confirm that the reverse postorder cursor identifies the root of the current inorder range, followed by its right subtree.
Interview review checklist
- Explain why reverse postorder partition matches the structure of this input.
- State the invariant in one sentence before tracing code: The reverse postorder cursor identifies the root of the current inorder range, followed by its right subtree.
- Derive O(n) time and O(n) space from how many times each element or state is visited.
- Test the boundary explicitly: Building left first would consume roots in the wrong order.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 105. Construct Binary Tree from Preorder and Inorder Traversal · Next: 117. Populating Next Right Pointers in Each Node II