# Tutorial :Recursion - when would you use it and when wouldn't you use it [closed]

### Question:

Recursion - when would you use it and when wouldn't you use it?

### Solution:1

I use recursion whenever I encounter a problem that requires recursion.

### Solution:2

Generally, if you can conceptualize the problem with a tree data structure then you can use recursion to navigate the tree.

### Solution:3

Very language dependent. Be very careful with languages like Ruby that don't have very good tail call optimization. True functional languages handle recursion better. Make sure you know about memoization before you start to rely on it too much. Where I really use it is when I know the full bounds of the inputs and outputs. If I know I won't ever, ever, go 100 levels deep then I'll use it (in Ruby, at least), otherwise I find a different pattern. I wish recursion was faster, because so often I find a really neat 2 line solution that I love, but that doesn't preform stably or quickly so I'll have to replace it.

### Solution:4

I would use it when it made a problem easier and I had a large amount of stack memory (in case of a large stack).

I wouldn't use it if stack memory was at a premium (so the call stack doesn't grow too large and cause the stack to overflow and your application to fail).

### Solution:5

I would NOT use it if you know your language / environment has a limitation on the calling stack depth. I remember working with an early version of Lotus Notes which had a limit of something like 16 levels deep - which would make almost any use of recursion impossible.

### Solution:6

I would use it if, and only if, it was obviously the correct solution and no other method could possibly be correct.

Perhaps for a factorial function, although probably not. Try the Fibonnaci sequence

``f(n) = f(n - 1) + f(n - 2), f(0) = f(1) = 1  ``

if you want an example of how something apparently solvable by recursion can grow very ugly very quickly.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »