A recursive method solves a problem by calling itself on a smaller instance of the same problem, until a base case returns without another call.
Mental model: recursion is the call stack as a stack data structure. If you cannot name the base case and the shrinking argument, you do not yet have a recursive solution — you have a future StackOverflowError.
static int factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("n");
}
if (n == 0 || n == 1) {
return 1; // base
}
return n * factorial(n - 1);
}
n must move toward it (n - 1, a shorter string, a smaller list, a child node).n < 0). Do not recurse on invalid input.factorial(20) fits in long. factorial(21) overflows long. Recursion does not fix overflow.// Incorrect — never hits a base if n starts negative
static int bad(int n) {
if (n == 0) return 1;
return n * bad(n - 1);
}
Each call waits for the inner call to return, then finishes (for example the multiply in factorial). Deep recursion → many frames → StackOverflowError (an Error, not an exception you recover from in ordinary code).
walk(node.next).O(log n) — recursion is natural. A degenerate tree is a list — same warning.| Recursion | Iteration | |
|---|---|---|
| Natural fit | Trees, divide-and-conquer, backtracking | Sequences, running totals, I/O loops |
| State | Frames (implicit stack) | Your variables / explicit Deque |
| Risk | Stack overflow, accidental exponential time | Off-by-one, forgotten updates |
Anything recursive can be written with an explicit stack. Professionals recurse when the code is clearer and the depth is bounded (or they convert once it is not).
static int factorialIter(int n) {
int acc = 1;
for (int i = 2; i <= n; i++) {
acc *= i;
}
return acc;
}
// Exponential time — do not ship
static long fib(int n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
fib(n) recomputes the same subproblems. fib(40) is already painful. Use a loop or memoization.O(n log n) because the pieces do not overlap that way. Draw the call tree.gcd(a, b) = gcd(b, a % b), base b == 0. Fast and deep-safe for integers.static int gcd(int a, int b) {
return b == 0 ? Math.abs(a) : gcd(b, a % b);
}
Public API takes the user’s arguments. A private helper carries indexes or accumulators so you do not copy arrays on every call.
static boolean contains(int[] a, int x) {
return contains(a, x, 0);
}
private static boolean contains(int[] a, int x, int i) {
if (i == a.length) return false;
if (a[i] == x) return true;
return contains(a, x, i + 1);
}
Map or array of already-computed answers. Clear about identity of the key.f(n) calls f(n)).StackOverflowError and retrying — do not. Rewrite.~ Good luck with your revision! ~