Lecture 8 Tree Recursion
- Questions
- Can we draw a tree structure for recursion that isn’t specifically tree recursion?
- Would it just be one branch?
- Can we draw a tree structure for recursion that isn’t specifically tree recursion?
- Order of Recursive Calls
- Pickup where you left off on the previous function
- Each cascade frame is from a different call to cascade
- Until the return value appear, call has not been completed yet
- Put the base cases first in recursive functions
- base case - smallest case in your problem
- Tree Recursion
- Tree-shaped processes arise whenever executing the body of a recursive function makes more than one recursive call
- A Tree-Recursive Process
- The computational process of fib evolves into a tree structure
- Repetition in Tree-Recursive Computation
- Fibonacci sequence isn’t super efficient as many values are calculated many times
- Recursive vs Iterative
- Recursive
- Visually represents recursive definition
- Computation happens in many frames
- Iterative
- Easy to follow calculations
- Computation in one frame
- Recursive
- Example: 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 increasing order
- No duplicates for combinations
- Example:
- counter_partitions(6,4)
- 2 + 4 = 6
- counter_partitions(6,4)
-
Recursive Decomposition
- finding simpler instances of the problem
- Explore two possibilities:
- Use at least one 4
- Don’t use any 4
- Solve two simpler problems
- Use at least one 4
- After you use 4, then it becomes count_partitions(2,4)
- Don’t use any 4
- If you don’t use 4, then it becomes count_partitions(6,3)
- Use at least one 4
def count_partitions(n,m): if n==0: return 1 elif n<0: #failure case: overshooting return 0 elif m==0: #failure case: there is no possible values for m when it is 0 return 0 else: with_m = counter_partitions(n-m, m) without_m = count_partitions(n, m-1) return with_m + without_m
- Tree recursion
- multiple recursive calls within its body, each modeling a specific decision
- base cases may not always be apparent, and sometimes working through recursive calls can help you figure them out