Recursion in computer science is a sometimes tricky concept to wrap one's head around.
People often say that to understand recursion, one must first understand recursion! But it needn't be as daunting as it seems. Recursion at in its simplest form is simply a function call itself. My instructors have always told me to ignore complexity and let the recursive call do the work for me. Turns out, they're right!
Let's cover the basics first. In order for a function to be a working recursive function, it needs two things: a base case that serves as a stopping condition, and a recursive call that calls the selfsame function again(hopefully with a slightly modified argument)..
Recursion is great for iterating through lists and trees. It does the heavy lifting of sifting through all of the possibilities for us, and does so quite elegantly might I add.
I would say that the biggest shortfall of using recursion would be the effect that it can have on time complexity of operations. Using recursion where a simple for loop might have sufficed can cause your code's performance to suffer. One technique to hedge against increased time complexity, is memoization. It's used to store the results of expensive function calls and return the cached result when the same input occurs. Memoization can help a recursive function actually run faster than an iterative function if written correctly.
Be judicious and remember that with great power comes great responsibility, and remember that with great power comes great responsibility, and remember...
Top comments (0)