r/computerscience • • May 03 '21

When to use recursion?

So I am getting a little bit ahead of myself here, I'm still in high school and I'm entering (hopefully) AP Java next year (or computer science A). One of the topic there is recursion, and I've done a little digging, and I find recursion really interesting, but what I was wondering was when do programmers use recursion? Like, can a for loop just do the job or does it help with computer memory and processing, when is the best time to use recursion?

141 Upvotes

80 comments sorted by

View all comments

163

u/usernameistakencry May 03 '21
  1. Anything that can be done with recursion can be done with a loop.

  2. Some problems are much much easier to solve with recursion , example: most tree algorithms and graph algorithms.

  3. Recursion can easily solve a problem but can be really really bad in terms of memory use for example Fibonacci numbers. But there are things like caches you can use to improve these problems so it is a trade off sometimes.

3

u/Henrique_FB May 03 '21

Wait, genuine question, how do you do stuff like going back on a binary tree with a loop?

20

u/Leridon May 03 '21

By manually keeping a stack of nodes that are left to traverse. This emulates the way the runtime stack would have kept the same information.

6

u/Radeusgd May 03 '21

Yeah so it is basically re-implementing the recursive calls, just using your own custom stack over which you have more control.