Recurrences & the Recursion Tree
In short: read a recurrence straight off recursive code — one term per
recursive call, plus one term f(n) for everything else the call does — then
draw it as a tree. Every node's own work is its badge; add the badges on
each level, then add the levels. Three shapes decide the outcome: levels that
shrink (the root dominates), tie (n^k log n), or grow (the leaves decide).
The master theorem is just a one-line rule for spotting which shape you have.

In the merge sort lesson you looked at a split tree and concluded "n work per level, log n levels, so O(n log n)". That argument was about one picture. Tunebox runs a dozen recursive functions, and you need a method that gives the cost of any of them.
This section builds Tunebox's cost lab: instruments that measure the code you already wrote and check it against what you proved on paper. The first instrument is the method itself: turn the code into a recurrence, then solve it with a recursion tree.
From code to a recurrence
A recurrence gives a function's cost in terms of its cost on smaller inputs. Read it off the code with two rules:
- Every recursive call becomes a term
T(size of that call). - Everything else the body does (the loops, the merge, the slicing) becomes
one extra term, written
f(n).
Here is your merge sort from section 3, annotated:
def merge_sort(items):
if len(items) <= 1: # base case: constant work
return list(items)
mid = len(items) // 2
left = merge_sort(items[:mid]) # T(n/2)
right = merge_sort(items[mid:]) # T(n/2)
return merge(left, right) # about n steps: f(n) = nTwo calls on half the list, plus a merge that touches all n items:
The same reading works for everything you wrote earlier:
| your code | recursive calls | other work | recurrence |
|---|---|---|---|
| binary search (section 3) | one, on half | a comparison | |
| merge sort | two, on halves | the merge | |
| quick sort, sorted input, last pivot | one, on n − 1 | the partition | |
| naive Fibonacci (section 6) | two, on n−1 and n−2 | an addition |
Try one you have not seen. This function loops over its input, then makes three calls, each on half of it:
work = 0
def split3(n):
global work
if n <= 1:
return
for _ in range(n):
work += 1
split3(n // 2)
split3(n // 2)
split3(n // 2)
split3(8)
print(work)Getting the number of calls right matters more than anything else. This model of binary search gets it wrong:
Binary search on 1,024 titles looks at about 11 titles, so this should print 11. It prints 2047 because the model thinks the search visits both halves.