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

0500020004000ncount
Measured
Table
ncount
817
1633
3265
64129
128257
256513
5121,025
10242,049
20484,097
40968,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)
  1. The recursion tree has a node per call; constant work per call.
  2. Levels double: 1 + 2 + 4 + … + n ≈ 2n calls. A geometric series dominated by its last term.
  3. 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.