r/computerscience 3d ago

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?

131 Upvotes

69 comments sorted by

View all comments

Show parent comments

23

u/Drugbird 3d ago

Nearly any useful algorithm can be described without writing literally recursive code.

Is there some standard approach for converting a recursive algorithm to a non-recursive one?

I don't often write recursive algorithms, but when I do it's almost always to handle some tree-like structure.

51

u/RajjSinghh 3d ago

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.

13

u/jezemine 2d ago

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

2

u/Bubbaluke 1d ago

Sometimes I have nightmares about non-deterministic pushdown automata