πTree Recursion
Many, many function calls.
We've now seen what standard recursion looks like β a function that calls itself. We'll now make our lives slightly more complicated by introducing tree recursion β a function that calls itself not once but multiple times.
A classic example of tree recursion is a Fibonacci Sequence. In this sequence, a given number is the sum of the previous two numbers. The sequence goes as follows:
Let's write this in code!
An important observation here: Why do we have n==0
as a base case, even when that is not acceptable as an input. It's because while the user might never give us n
as the value for n
, our recursive calls might. Consider the case fib(2)
β which makes the recursive calls fib(1)
and fib(0)
Β β 1 + 0 β 1, as required!
We could have written something like n==1 or n==2
as our base case as well, but using this structure instead allows us to introduce the idea of base cases for inputs invalid for the user but valid for the recursive calls.
Regardless, something like fib(4)
looks like the following in terms of recursive calls:
It is easier to visualize by representing function calls as nodes in a tree:
As you can see, this looks like an upside down tree (kinda... I wouldn't think too hard about it, most computer scientists don't go outside very often). The big idea here is that, at every stage, we make two recursive calls and then combine them in some way. This is tree recursion!
Last updated