LeetCode 236: Lowest Common Ancestor of a Binary Tree is a Medium binary tree general problem. This Python walkthrough develops a postorder target propagation 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 | postorder target propagation |
| Complexity | O(n) time and O(h) recursion 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, return a node when it is a target or when targets are found in both child subtrees; otherwise propagate the one non-null result. The invariant worth writing beside the code is: A non-null return means that subtree contains at least one target, and the first node receiving two results is their lowest common ancestor.
Step-by-step algorithm
- Identify the input state consumed by
lowestCommonAncestor(root, p, q)and initialize the data required by the postorder target propagation pattern. - Return a node when it is a target or when targets are found in both child subtrees; otherwise propagate the one non-null result.
- After each update, verify the page’s central invariant: A non-null return means that subtree contains at least one target, and the first node receiving two results is their lowest common ancestor.
- Finish only after the boundary behavior is covered: One target may be an ancestor of the other.
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 lowestCommonAncestor(self, root, p, q):
if not root or root is p or root is q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return left or rightReading the implementation
The main entry point is lowestCommonAncestor(root, p, q). The named working state includes left, right; those variables make the postorder target propagation state visible instead of hiding it in incidental control flow.
The entry point is recursive: each call reduces the remaining tree, graph, or search state before combining the returned information. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, return a node when it is a target or when targets are found in both child subtrees; otherwise propagate the one non-null result.
Correctness argument
Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.
Inductive step. Return a node when it is a target or when targets are found in both child subtrees; otherwise propagate the one non-null result. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so a non-null return means that subtree contains at least one target, and the first node receiving two results is their lowest common ancestor.
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(h) recursion 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.
lca_tree=tree([3,5,1,6,2,0,8,None,None,7,4]); assert Solution().lowestCommonAncestor(lca_tree,lca_tree.left,lca_tree.right) is lca_treeCommon mistakes and edge cases
- Problem-specific boundary: One target may be an ancestor of the other.
- 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 a non-null return means that subtree contains at least one target, and the first node receiving two results is their lowest common ancestor.
Interview review checklist
- Explain why postorder target propagation matches the structure of this input.
- State the invariant in one sentence before tracing code: A non-null return means that subtree contains at least one target, and the first node receiving two results is their lowest common ancestor.
- Derive O(n) time and O(h) recursion space from how many times each element or state is visited.
- Test the boundary explicitly: One target may be an ancestor of the other.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 222. Count Complete Tree Nodes · Next: 199. Binary Tree Right Side View