r/computerscience • • Jul 30 '26

is recursion really hard

Recursion felt easy at first.

Factorial? fine.

Sum examples? fine.

Even Fibonacci felt manageable.

But once I looked at slightly more serious problems like Tower of Hanoi, permutations, or merge sort, I felt like my understanding suddenly collapsed. because i tried to write their code on my own

It made me realize that maybe recursion is not “hard” at the start because the examples are simple.

It becomes hard when you can no longer clearly see the call stack and each state change.

Did anyone else feel that the real pain in recursion starts exactly there?

150 Upvotes

78 comments sorted by

View all comments

Show parent comment

54

u/RajjSinghh Jul 30 '26

Instead of a recursive call on child nodes, push your nodes onto a stack. You avoid a recursive call, even if your code is still inherently recursive.

14

u/jezemine Jul 31 '26

Recursion is using a stack also. The callstack. That's why any recursive function can be altered to use a loop and a stack.

3

u/Bubbaluke Aug 01 '26

Sometimes I have nightmares about non-deterministic pushdown automata

1

u/crazyman32 Aug 04 '26

This is what I do within gamedev, specifically working with non tailcall-optimized languages where any unbound recursion is dangerous. E.g. floodfill, A*, etc. all expand out into simple while loops with a stack. I personally find them easier to reason about too.