In: Computer Science
In what case(s) would you use recursion over iteration and which approach is more memory efficient and why when you compare which approach would you say is faster and why?
One must use recursion for complex problems like the ones which can have many iterative loops like the tree traversal problem since a tree is basically a non uniform data structure and only the height of a tree is known and we dont have a clear idea about the number of nodes so traversing a tree can be hectic task if we use iteration like for and while loop however recursion makes the tree traversal easy by running a particular task until and unless the final condition is met a recursion basically divides a complex problems into different parts which makes the problem much easier to solve .
One must also use recursion where there is a repetative pattern like in fibonacci series which is type of series in which the third term is the sum of the other two and this type of program usse a dynamic approach as the variable changes in order to further calculate the fibonacci series.
Though recursion is not memory efficient as compared to iteration because recursion stores the data in a stack and then back tracks it but it helps us to solve complex problems easily and iteration does not use much space so recursion in not memory efficient.
Recursion can be slower because every time it needs to allocate a new stack until and unless it is optimized it basiclly depends upon the kind of problem we approach for example in the case of tree traversal one needs to write many for loops to iterate through a tree while there is not much iteration in recursion and program can be written in simple manner howevere generally iteration is faster than recursion