3 ms·
I think it's worth distinguishing between recursion as a conceptual framework for breaking down problems, and recursion as "writing functions that call themselv
by dTal 4y ago
I think it's worth distinguishing between recursion as a conceptual framework for breaking down problems, and recursion as "writing functions that call themselves in a given programming language".
Recursion-the-concept is sometimes the only way to solve a problem. If you want to calculate the total number of leaves in a tree structure, the algorithm is clear: recursively sum the number of leaves in each branch. Recursion is just a way of saying "for this loop, we will need to maintain some kind of stack to track our location".
Conveniently, most languages have a stack built-in in the form of a function call graph. This allows us to elegantly and concisely express recursive algorithms by simply writing functions that call themselves, exactly like the formal definition of recursion. You don't have to do it that way - you can create your own stack data structure and manually manage it, and it'll still be a recursive algorithm. But that's probably a bad idea unless you have good reason to believe that working with your language's built-in stack has limitations that are important for your use case - limited size or poor performance, perhaps.