Exercise 18 of 30 · intermediate · recursion · linear · recurrences · trees
Two halves plus constant work
The code
def count_nodes(node):
if node is None: return 0
return 1 + count_nodes(node.left) + count_nodes(node.right)Solve T(n) = 2T(n/2) + O(1).
Count: calls on a perfect tree with n nodes.
Measured counts
Table
| n | count |
|---|---|
| 8 | 17 |
| 16 | 33 |
| 32 | 65 |
| 64 | 129 |
| 128 | 257 |
| 256 | 513 |
| 512 | 1,025 |
| 1024 | 2,049 |
| 2048 | 4,097 |
| 4096 | 8,193 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n)
- Extra space
- Θ(height) stack
- Exact count
- 2n + 1 calls (n nodes plus n + 1 empty children)
- The recursion tree has a node per call; constant work per call.
- Levels double: 1 + 2 + 4 + … + n ≈ 2n calls. A geometric series dominated by its last term.
- So Θ(n), not Θ(n log n): the work per level is not constant across levels.
Common mistake: Assuming every "two recursive halves" recursion is n log n. It depends on the non-recursive work.
Check: measured count ÷ (n) settles near 2.00 for large n.