Recursion

What is recursion?

In general, recursion is when a function calls itself.

When our code runs a loop (for loop, while loop, etc), doing the same process over and over again until the loop ends, that’s called ‘iterating’ through inputs. Alternatively, when our code calls itself, doing the same process over and over again until some base level condition is met, that’s called ‘recursing’ through them. Much of what can be done via iterating can be done recursively, and vice versa.

There are many trade offs between iteration and recursion (see video below for more info). Recursion can be difficult to wrap your head around, because you need to keep track of what your data looks like in different calls to the function, but often it used in situations when the iterative alternative, usually a while loop, would be so visually confusing that recursion actually simplifies the code you must write significantly.

It is hugely important to be familiar with both methodologies (iterative and recursive), particularly for a) interviews, and b) data structures called ‘trees’ and ‘graphs’. Graphs are beyond the scope of this course, but we will look at trees in the coming weeks.

To learn more, please visit this link.