Recursion Vs. Iteration

Recursion and iteration are alternative ways of expressing repetition in an algorithm.

Which technique is better to use-recursion or iteration? This question has no simple answer. The choice usually depends on two issues:

Recursion might not be the most efficient way to implement an algorithm. Each time a function is called, there is a certain amount of "overhead" that takes up memory and system resources. When a function is called from another function, all the information about the first function must be stored so that the computer can return to it after executing the new function.

So what can be done about this? You'll need to decide up front whether recursion is necessary. Often, you'll decide that an iterative implementation would be more efficient and almost as easy to code. It has been proven mathematically that any problem that can be solved with recursion can also be solved with iteration, and vice versa. However, there are certainly cases where recursion is the best choice, and in these instances you should not shy away from using it. Recursion is often a useful tool when working with data structures such as trees.