3 ms·
I think the best way to master recursion is to think of it as a data structure stored on the actual stack. As you enter you are creating elements (state) and s
by lmilcin 6y ago
I think the best way to master recursion is to think of it as a data structure stored on the actual stack.
As you enter you are creating elements (state) and store it on the stack and as you exit you are reducing elements.
When thinking this way you can notice a lot of interesting points about recursion.
For example, a simple way to test if you can get away with tail recursion is if you can reduce elements as you enter. It means you don't have to store elements as you enter -- no need for data structure on the stack == no need for actual recursion.
Another observation to remember is you can write that as an actual stack and implement any recursive problem (for example tree traversal) without recursion. Your data structure contains the state that you need.
I would sometimes write recursive solution first and then see if it might be better off rewritten to use a separate stack and loop.
Yet another important observation is that on a program stack you don't normally access anything than top of the stack. But for your algorithm having access to all previous levels might be useful. That's where writing it as a separate data structure might be advantageous.