More on recursion
More on recursion
A few comments about recursion:1. When writing a recursive method, you need to assume that the recursive calls will work; that is, they meet their specifications. This is called the recursive "leap of faith". You need to believe that your recursive method will work correctly, even before you have finished writing it.
2. Note that when you write a recursive method you are acting as both an application writer and an implementation writer. That means that understanding the semantics of the interface is especially important. In particular, if you call a recursive method that returns a value, you probably need to use that value.
3. Identify base cases; that is, nonrecursive cases. In working with data structures, this usually means an empty data structure.
4. Variables declared within a recursive method are not global. A new instance of the variable is created each time the method is called. The same rule applies to parameters passed to recursive methods, and to the implicit parameter "this".
5. An endless series of recursive calls will lead to a "Stack Overflow" exception.
6. Avoid making the same recursive call more than once. This can lead to serious inefficientcy problems.
7. Helper methods can be helpful. Often the exact specification of a method you are to write does not lend itself well to a recursive solution, but recursion can be used to solve a similar problem. Write the solution to the similar problem as a recursive helper method, then use that method to solve the original problem.