TExcelTAD
Home › Foundations of Algorithm Analysis › Recursion Trees

Recursion Trees

A substitution proof needs a guess, and a recursion tree is the standard way to make one. The tree draws every call of the recursion as a node, labelled with the work that call does outside its own recursive calls. Summing the labels level by level turns the recurrence into an ordinary sum, often a geometric series. The answer it gives is usually right, but because the drawing tends to gloss over floors, ceilings and the last level, the careful habit is: guess with the tree, prove with substitution.

The Divide-and-Conquer Recurrences lesson sketches the idea for the balanced case. This lesson does the bookkeeping in full and then handles a tree whose branches have different lengths.

Building the tree

Take T(n)=2T(n/2)+n2T(n) = 2T(n/2) + n^2 with T(1)=1T(1) = 1, and let nn be a power of 2. The root is the top-level call: it costs n2n^2 by itself and has two children of size n/2n/2. Each child costs (n/2)2(n/2)^2 and has two children of size n/4n/4, and so on until the size reaches 1.

text
level 0                n^2                              level cost  n^2
                    /        \
level 1        (n/2)^2      (n/2)^2                                 n^2 / 2
               /    \        /    \
level 2   (n/4)^2 (n/4)^2 (n/4)^2 (n/4)^2                           n^2 / 4
             ...                                                     ...
level i   2^i nodes, each (n/2^i)^2                                 n^2 / 2^i
             ...
level lg n   n leaves, each T(1) = 1                                n

Three numbers describe any such tree for T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n):

  • Depth. The size at level ii is n/bin/b^i, which reaches 1 at i=log⁡bni = \log_b n. So there are log⁡bn+1\log_b n + 1 levels.
  • Nodes per level. Every node has aa children, so level ii has aia^i nodes, and the bottom level has alog⁡bn=nlog⁡baa^{\log_b n} = n^{\log_b a} leaves.
  • Cost of level ii. aif(n/bi)a^i f(n/b^i).

For the tree above, level ii costs 2i(n/2i)2=n2/2i2^i (n/2^i)^2 = n^2/2^i, so

T(n)=∑i=0lg⁡n−1n22i+n<n2∑i=0∞(12)i+n=2n2+n.T(n) = \sum_{i=0}^{\lg n - 1} \frac{n^2}{2^i} + n < n^2 \sum_{i=0}^{\infty} \left(\frac{1}{2}\right)^i + n = 2n^2 + n.

The level costs form a decreasing geometric series, whose sum is at most a constant times its first term, so T(n)=Θ(n2)T(n) = \Theta(n^2): the root alone does a constant fraction of all the work.

Three shapes of tree

The same bookkeeping gives three typical pictures. The program prints the level costs for three recurrences with n=64n = 64.

python · try it yourself
def level_costs(a, f, n):
    costs, size, nodes = [], n, 1
    while size >= 1:
        costs.append(nodes * f(size))
        size, nodes = size // 2, nodes * a
    return costs

n = 64
for name, a, f in [("2T(n/2) + n^2", 2, lambda m: m * m),
                   ("2T(n/2) + n  ", 2, lambda m: m),
                   ("8T(n/2) + n^2", 8, lambda m: m * m)]:
    c = level_costs(a, f, n)
    print(f"{name}: {c}  total {sum(c)}")
2T(n/2) + n^2: [4096, 2048, 1024, 512, 256, 128, 64]  total 8128
2T(n/2) + n  : [64, 64, 64, 64, 64, 64, 64]  total 448
8T(n/2) + n^2: [4096, 8192, 16384, 32768, 65536, 131072, 262144]  total 520192
  • Decreasing (first line): each level costs half the one above, the sum is dominated by the root, Θ(f(n))=Θ(n2)\Theta(f(n)) = \Theta(n^2).
  • Equal (second line): all lg⁡n+1\lg n + 1 levels cost nn, so T(n)=n(lg⁡n+1)=Θ(nlg⁡n)T(n) = n(\lg n + 1) = \Theta(n \lg n). Here 64⋅7=44864 \cdot 7 = 448.
  • Increasing (third line): each level costs twice the one above, the sum is dominated by the leaves, Θ(nlog⁡ba)=Θ(n3)\Theta(n^{\log_b a}) = \Theta(n^3). Indeed the total 520 192520\,192 is just under 2⋅643=524 2882 \cdot 64^3 = 524\,288.

The geometric series facts that make this work:

∑i=0kri=rk+1−1r−1,∑i=0kri<11−r for 0<r<1,∑i=0kri<rr−1 rk for r>1.\sum_{i=0}^{k} r^i = \frac{r^{k+1} - 1}{r - 1}, \qquad \sum_{i=0}^{k} r^i < \frac{1}{1 - r} \text{ for } 0 < r < 1, \qquad \sum_{i=0}^{k} r^i < \frac{r}{r - 1} \, r^{k} \text{ for } r > 1.

In words: a geometric sum with ratio below 1 is Θ\Theta of its first term, and one with ratio above 1 is Θ\Theta of its last term. The master theorem is these three pictures turned into a theorem.

An unbalanced tree

Now a recurrence the master theorem does not cover, because the two subproblems have different sizes:

T(n)=T(n/3)+T(2n/3)+n.T(n) = T(n/3) + T(2n/3) + n.

Such recurrences arise when a split is lopsided, for example a quicksort whose pivot always lands at the one-third mark. Draw the tree. The root costs nn; its children cost n/3n/3 and 2n/32n/3, together again nn; the four grandchildren cost n/9n/9, 2n/92n/9, 2n/92n/9 and 4n/94n/9, together again nn. As long as no branch has reached the bottom, every level costs exactly nn.

The branches do not all have the same length, though. The path that always takes the third shrinks fastest and reaches size 1 after log⁡3n\log_3 n levels; the path that always takes two thirds is the longest, with log⁡3/2n\log_{3/2} n levels. So:

  • the first log⁡3n\log_3 n levels are full and cost nn each, giving at least nlog⁡3nn \log_3 n;
  • there are at most log⁡3/2n+1\log_{3/2} n + 1 levels, each costing at most nn, giving at most about nlog⁡3/2nn \log_{3/2} n.

Both bounds are Θ(nlg⁡n)\Theta(n \lg n) (logarithms of different bases differ by a constant factor), so the guess is T(n)=Θ(nlg⁡n)T(n) = \Theta(n \lg n). The program builds the tree for n=729=36n = 729 = 3^6 with integer sizes and prints each level.

python · try it yourself
n = 729
level, depth = [n], 0
print("depth  nodes  cost of level")
while level:
    print(f"{depth:5}  {len(level):5}  {sum(level):6}")
    level = [s for x in level if x >= 3 for s in (x // 3, x - x // 3)]
    depth += 1
depth  nodes  cost of level
    0      1     729
    1      2     729
    2      4     729
    3      8     729
    4     16     729
    5     32     729
    6     64     729
    7    114     716
    8    158     661
    9    186     561
   10    162     407
   11    112     251
   12     92     164
   13     26      51
   14     18      29
   15      2       4
   16      2       3

The first seven levels (depths 0 to 6, that is log⁡3729+1\log_3 729 + 1 of them) cost exactly 729. After that the short branches have stopped, the levels thin out, and the deepest branch ends at depth 16; for comparison log⁡3/2729≈16.3\log_{3/2} 729 \approx 16.3.

Proving the guess

Now the substitution method turns the guess into a theorem. Suppose T(k)≤d klg⁡kT(k) \le d\,k \lg k for all smaller kk. Then, ignoring rounding,

T(n)≤d n3lg⁡n3+d 2n3lg⁡2n3+n=d nlg⁡n−d n(13lg⁡3+23lg⁡32)+n=d nlg⁡n−d n(lg⁡3−23)+n≤d nlg⁡nif d≥1lg⁡3−2/3≈1.089.\begin{aligned} T(n) &\le d\,\frac{n}{3} \lg \frac{n}{3} + d\,\frac{2n}{3} \lg \frac{2n}{3} + n \\ &= d\,n \lg n - d\,n \left( \frac{1}{3} \lg 3 + \frac{2}{3} \lg \frac{3}{2} \right) + n \\ &= d\,n \lg n - d\,n \left( \lg 3 - \frac{2}{3} \right) + n \\ &\le d\,n \lg n \qquad \text{if } d \ge \frac{1}{\lg 3 - 2/3} \approx 1.089. \end{aligned}

The lower bound T(n)≥d′ nlg⁡nT(n) \ge d'\,n \lg n follows the same way with d′≤1/(lg⁡3−2/3)d' \le 1/(\lg 3 - 2/3). So the constant in front of nlg⁡nn \lg n should approach about 1.0891.089. A numerical check with floors (subproblems ⌊n/3⌋\lfloor n/3 \rfloor and n−⌊n/3⌋n - \lfloor n/3 \rfloor, base cost 1 below 3):

python · try it yourself
import math
from functools import lru_cache

@lru_cache(None)
def T(n):
    if n < 3:
        return 1
    return T(n // 3) + T(n - n // 3) + n

print("predicted constant 1 / (lg 3 - 2/3) = %.4f" % (1 / (math.log2(3) - 2 / 3)))
for n in [10**2, 10**3, 10**4, 10**5, 10**6]:
    print(f"n = {n:8}   T(n) / (n lg n) = {T(n) / (n * math.log2(n)):.4f}")
predicted constant 1 / (lg 3 - 2/3) = 1.0890
n =      100   T(n) / (n lg n) = 1.1409
n =     1000   T(n) / (n lg n) = 1.1183
n =    10000   T(n) / (n lg n) = 1.1098
n =   100000   T(n) / (n lg n) = 1.1041
n =  1000000   T(n) / (n lg n) = 1.1011

The ratio creeps down towards the predicted constant, exactly what the proof says. The tree supplied the guess Θ(nlg⁡n)\Theta(n \lg n), the proof supplied the certainty, and the computation caught no mistake in either.

Common mistake: in an unbalanced tree, assuming every level costs nn all the way down and multiplying by the longest depth gives a valid upper bound but not a lower bound. The lower bound has to use the shortest depth, the last level that is still full.

Test yourself

In the recursion tree of T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n), how many nodes are on level ii, and what does each cost?

  1. bib^i nodes, each f(n/ai)f(n/a^i)
  2. aia^i nodes, each f(n/bi)f(n/b^i)
  3. ii nodes, each f(n)f(n)
  4. aa nodes, each f(n/b)f(n/b)

The level costs of a recursion tree are n2,n2/2,n2/4,…n^2, n^2/2, n^2/4, \ldots. What is the order of the total?

  1. Θ(n2lg⁡n)\Theta(n^2 \lg n)
  2. Θ(n2)\Theta(n^2)
  3. Θ(n)\Theta(n)
  4. Θ(n3)\Theta(n^3)

For T(n)=T(n/3)+T(2n/3)+nT(n) = T(n/3) + T(2n/3) + n, which depth gives the lower bound T(n)≥nlog⁡3nT(n) \ge n \log_3 n?

  1. log⁡3/2n\log_{3/2} n, the longest branch
  2. log⁡3n\log_3 n, the depth down to which every level is still full
  3. lg⁡n\lg n
  4. n/3n/3

Why is a recursion tree usually followed by a substitution proof?

  1. Because trees only work for powers of 2
  2. Because the tree is a quick way to guess, but it tends to gloss over floors, ceilings and the last levels
  3. Because the tree always overestimates
  4. Because the master theorem requires it