Recursion &
Tree Recursion
annietang@berkeley.edu�anniewtang.github.io/cs61a
links.cs61a.org/annie-disc
Announcements
Agenda
Recursion
The Setup & The Solution(s)
Iterative Solution
Situation
The Setup & The Solution(s)
Situation
Recursive Solution
how can we implement this in code?
write a function: factorial(n)
Functional Abstraction
understanding the domain & range of a function
The Three Steps to Recursion
(classic)
step 1:
the base case
How does one choose a base case?
consider the following scenarios!
Starting from the recursive call
for non-intuitive base cases
step 2:
use recursion to solve the smaller problem
tackling that “smaller” problem
step 3:
solve the main problem
using your recursive step
factorial(5)�= 5 * 4 * 3 * 2 * 1�= 5 * factorial(4)
Tree Recursion
Tree Recursion (overview)
Tree recursion ⇒ Recursion by cases.
Let’s say you’re trying to solve a problem using recursion, and while doing so you realize:
NOTE:
Later when we learn about “Trees” (an abstract data type), you’ll see us applying recursion on trees.
Our recursive strategy on trees oftentimes uses tree recursion
Overall, recursion takes a lot of practice to get used to!
so don’t worry if you find it difficult in the beginning :)