# Tree Recursion - Fri, Sep 20

## Order of Recursive Calls -- The Cascade Function

``````def cascade(n):
if n < 10:
print(n)
else:
print(n)
print(n)``````

## Tree Recursion

When a function calls itself within its body more than once.

``````def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-2) + fib(n-1)``````

See the slides for a tree graphic of calling `fib(5)`.

## Counting Partitions

The number of partitions of a positive integer n, using parts up to size m, is the number of ways in which n can be expressed as the sum of positive integer parts up to m in non-decreasing order.

Recursive decomposition: finding simpler instances of the problem.

`count_partitions(6, 4)`:

• Explore two possibilities:
• Use at least one 4
• Don't use any 4
• Solve two simpler problems:
• `count_partitions(2, 4)`
• `count_partitions(6, 3)`

Tree recursion often involves exploring different choices.

``````def count_partitions(n, m):
if n == 0:
return 1
elif n < 0:
return 0
elif m == 0:
return 0
else:
with_m = count_partitions(n-m, m)
without_m = count_partitions(n, m-1)
return with_m + without_m``````