LeetCode 222: Count Complete Tree Nodes is a Medium binary tree general problem. This Python walkthrough develops a perfect-subtree detection 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 | perfect-subtree detection |
| Complexity | O(log^2 n) time and O(log n) 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, compare leftmost and rightmost heights. Equal heights identify a perfect subtree whose size is computed directly; otherwise recurse. The invariant worth writing beside the code is: Equal extreme heights in a complete subtree imply every level is full.
Step-by-step algorithm
- Identify the input state consumed by
countNodes(root)and initialize the data required by the perfect-subtree detection pattern. - Compare leftmost and rightmost heights. Equal heights identify a perfect subtree whose size is computed directly; otherwise recurse.
- After each update, verify the page’s central invariant: Equal extreme heights in a complete subtree imply every level is full.
- Finish only after the boundary behavior is covered: An empty subtree has size zero; height counts must use the same convention.
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 countNodes(self, root):
def left_height(node):
height = 0
while node: height += 1; node = node.left
return height
def right_height(node):
height = 0
while node: height += 1; node = node.right
return height
if not root:
return 0
left, right = left_height(root), right_height(root)
if left == right:
return (1 << left) - 1
return 1 + self.countNodes(root.left) + self.countNodes(root.right)Reading the implementation
The main entry point is countNodes(root). The named working state includes height, left; those variables make the perfect-subtree detection 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, compare leftmost and rightmost heights. Equal heights identify a perfect subtree whose size is computed directly; otherwise recurse.
Correctness argument
Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.
Inductive step. Compare leftmost and rightmost heights. Equal heights identify a perfect subtree whose size is computed directly; otherwise recurse. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so equal extreme heights in a complete subtree imply every level is full.
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(log^2 n) time and O(log n) 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.
assert Solution().countNodes(tree([1,2,3,4,5,6]))==6Common mistakes and edge cases
- Problem-specific boundary: An empty subtree has size zero; height counts must use the same convention.
- 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 equal extreme heights in a complete subtree imply every level is full.
Interview review checklist
- Explain why perfect-subtree detection matches the structure of this input.
- State the invariant in one sentence before tracing code: Equal extreme heights in a complete subtree imply every level is full.
- Derive O(log^2 n) time and O(log n) recursion space from how many times each element or state is visited.
- Test the boundary explicitly: An empty subtree has size zero; height counts must use the same convention.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 173. Binary Search Tree Iterator · Next: 236. Lowest Common Ancestor of a Binary Tree