What is a recursive function and why are they extremely important in understanding algorithms? I’m going to explain with Data Structures and Algorithm Concepts: Recursion.
In the simplest terms possible, a recursive function is a function that calls upon a smaller version of itself in order to get to the solution. There is a pattern where by repeating the function over and over again, we can arrive at the solution. One of the key points of recursion is that it must have a base case, or a case when the recursion must stop. This is known as the end condition.
The reason I have matryoshka dolls as the photo above is because it is a very good visual representation of what recursion is like. Every single doll has a smaller version of itself inside until we reach the absolute smallest one — in which it no longer has any more smaller ones within it. In a recursive function, the smallest one would be the base case.
Let’s go over a simple problem that could utilize recursion. In a previous blog post, I went over reversing a string. Well, did you know that there’s a recursive solution to that which only requires 3 lines of code?