Data structures›Recursion and the call stack
Tutorial 8 of 13 · Data structures · Arrays and lists · BeginnerRecursion and the call stack
How a function solves a big job by calling itself on a smaller one.
6 lessons, the last is a challenge · about 1 h · Python and Java
Before you startYou can write a few lines of Python or Java: functions, if, loops and lists
You know what a stack is: a pile where you add and remove items only at the top (the stacks and queues tutorial)
Watch first · about 8 minRecursion: how a function that calls itself ever finishes. The narration uses an AI clone of the creator’s voice.What you’ll be able to do
- 1Write a recursive function with a base case and a recursive case, and say what each one is for.
- 2Follow a recursive call as frames added to and removed from the call stack, and say what has been worked out at any moment.
- 3Solve a problem on a list or a string by trusting the smaller call.
- 4Draw the call tree of a function that calls itself twice, count its calls, and remove the repeated work with a memo.
- 5Say what limits the depth of a recursion in Python and Java, and turn a recursion into a loop, using your own stack when it needs one.
Lessons
- 1A function that calls itselfFollow a countdown and a factorial, name the base case and the recursive case, and say what happens without a base case.13 min, up next
- 2The call stackFollow frames as they are added and removed, and say what has been worked out at each moment.12 min
- 3Recursion on lists and stringsAdd up a list and reverse a string by trusting the smaller call.11 min
- 4Branching recursionCount the calls in the tree of the Fibonacci function, and remove the repeats with a memo.13 min
- 5Depth, and when to loop insteadSay what limits depth, and rewrite a recursion as a loop, with your own stack if it needs one.10 min
- 6Final challenge: the frame detectiveFinal challenge · Read a stack during a run, fix a missing base case, change a recursion into a loop, and count calls.11 min
Next in this path
Next: 9 · Binary trees and traversals · 8 lessons · 1 h 39 min
Store things that sit under other things, like folders, and learn the ways to visit every one.
Playground
Try the same model with your own values. No checks, nothing recorded.
Open the playground