Skip to main content

Methods

Recursion

Complete lesson for Recursion using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Recursion

Section: Methods. Recursion in Java — base case, recursive case, call stack, types of recursion, real-world applications, backtracking, divide and conquer, and why the JVM does not tail-call optimize.

What is recursion?

  • Recursion is when a method calls itself (directly or indirectly) to solve a problem by breaking it into smaller copies of the same problem.
  • Every useful recursive method has two parts: a base case that stops, and a recursive case that calls itself with a smaller input.
  • Each call waits for the smaller call to finish. Results combine as the call stack unwinds.
  • Real-life analogy: Russian nesting dolls. Open a doll, find a smaller doll inside, repeat until the smallest solid doll (the base case), then close them in reverse order.
  • Real-life analogy: standing in a long queue and asking "how many people are ahead of me?" Each person asks the one in front, the first person says 0, and the answers come back adding 1 each step.
PartRoleExample (factorial)
Base caseStops further callsif (n <= 1) return 1;
Recursive caseCalls itself with a smaller inputreturn n * fact(n - 1);
ProgressEvery call must move toward the basen decreases by 1 each call
UnwindingCombine results while returning5 * 4 * 3 * 2 * 1 = 120
public class FactorialRec {
    static long fact(int n) {
        if (n < 0) throw new IllegalArgumentException("n must be >= 0");
        if (n <= 1) return 1;          // base case
        return n * fact(n - 1);        // recursive case
    }

    public static void main(String[] args) {
        System.out.println(fact(5));   // 120
    }
}

How recursion works (call stack)

  • Every method call pushes a new stack frame on the thread stack: parameters, local variables, and the return address.
  • When the base case returns, frames pop one by one and each caller finishes its pending work.
  • Too many frames (missing base case, or very deep input) throws java.lang.StackOverflowError.
  • Trace small inputs (n = 0, 1, 2, 3) on paper before trusting large ones.
// Trace fact(4):
// fact(4) -> 4 * fact(3)      push
// fact(3) -> 3 * fact(2)      push
// fact(2) -> 2 * fact(1)      push
// fact(1) -> 1                base case, start popping
// fact(2) = 2 * 1  = 2        pop
// fact(3) = 3 * 2  = 6        pop
// fact(4) = 4 * 6  = 24       pop

Design rules for a recursive method

  • Write the base case first. Then make a call that moves toward it (n - 1, mid, node.next, a shorter string).
  • Multiple base cases are normal: empty tree, n == 0 and n == 1 for Fibonacci, lo > hi for binary search.
  • Use a private helper (search(arr, key, lo, hi)) and a clean public method (search(arr, key)).
  • Do not do the same work twice: if two branches need the same sub-result, compute it once or memoize.

Types of recursion

  • Interviewers often ask you to name and identify these.
TypeMeaningJava example
DirectA method calls itselffact(n) calls fact(n - 1)
Indirect (mutual)Methods call each other in a cycleisEven(n) calls isOdd(n - 1)
TailRecursive call is the last actionreturn gcd(b, a % b);
Non-tail (head)Work remains after the call returnsreturn n * fact(n - 1);
LinearOne recursive call per invocationSum of array, linked-list length
Tree (multiple)Two or more calls per invocationfib(n - 1) + fib(n - 2), tree traversal
NestedArgument is itself a recursive callAckermann function A(m - 1, A(m, n - 1))

Classic recursion examples

ProblemBase caseRecursive idea
Factorialn <= 1 returns 1n * fact(n - 1)
Fibonaccin <= 1 returns nfib(n - 1) + fib(n - 2) (slow without memo)
Sum of digitsn == 0 returns 0n % 10 + sumDigits(n / 10)
Power x^nn == 0 returns 1x * power(x, n - 1) or halve n
GCD (Euclid)b == 0 returns agcd(b, a % b)
Binary searchlo > hi returns -1Recurse into the left or right half
Linked-list lengthnode == null returns 01 + length(node.next)
Tower of Hanoin == 0 does nothingMove n-1, move largest, move n-1

Tower of Hanoi

  • Move n disks from peg A to peg C using helper peg B. Only one disk moves at a time and a larger disk never sits on a smaller one.
  • Recursive idea: move n - 1 disks to the helper, move the largest disk to the target, then move the n - 1 disks onto it.
  • Number of moves is 2^n - 1 (3 disks need 7 moves).
public class Hanoi {
    static void move(int n, char from, char to, char via) {
        if (n == 0) return;                    // base case
        move(n - 1, from, via, to);
        System.out.println("Disk " + n + ": " + from + " -> " + to);
        move(n - 1, via, to, from);
    }

    public static void main(String[] args) {
        move(3, 'A', 'C', 'B');                // 7 moves
    }
}

Applications of recursion

  • Use recursion when the problem or the data naturally splits into smaller copies of itself.
  • It is strongest for hierarchical data (trees, folders, JSON), search with undo (backtracking), and divide-and-conquer algorithms.
Application areaWhy recursion fitsJava example
MathematicsThe definition refers to a smaller nFactorial, Fibonacci, GCD, power, nCr
SearchingEach step halves the search spaceRecursive binary search
Sorting (divide and conquer)Split, solve halves, combineMerge sort, quick sort
Tree data structuresEvery child is a smaller treeInorder / preorder / postorder, height, BST insert
Graph algorithmsVisit a node, then its unvisited neighboursDFS, cycle detection, connected components
BacktrackingChoose, recurse, undo, try the next choiceN-Queens, Sudoku solver, maze path, subsets
CombinatoricsInclude / exclude decisionsPermutations of a string, power set
Dynamic programmingRecursion plus a cache of sub-resultsMemoized Fibonacci, grid paths, coin change
File systemsA folder contains files and more foldersFolder size, directory tree printer with java.io.File
Parsing and compilersGrammar rules are nestedRecursive-descent expression parser, JSON / XML trees
Parallel computingSplit a big task into subtasksForkJoinPool with RecursiveTask
String problemsShrink the string each callPalindrome check, reverse a string
Graphics and gamesShapes repeat at smaller scalesFractals (Koch, Sierpinski), flood fill, game-tree minimax
PuzzlesState reduces step by stepTower of Hanoi

Real-world applications in Java projects

  • These are places where working Java developers meet recursion outside interview questions.
Real-world systemRecursive structureWhat the recursion does
File explorer / backup toolFolders inside foldersTotal size, search by extension, copy or delete a tree
E-commerce category menuCategory with sub-categoriesRender nested menus and breadcrumbs
Comment threadsReplies to repliesDisplay nested comments with indentation
Company org chartManager with reporting employeesHeadcount or salary total under a manager
JSON / XML processingObjects inside objectsWalk a Jackson JsonNode or DOM Node tree
Swing / JavaFX UIContainers inside containersEnable, disable, or style every child component
Paint programNeighbouring pixels of the same colourFlood fill (bucket tool)
Chess / tic-tac-toe AIGame tree of possible movesMinimax search for the best move
Calculator / compilerExpressions inside bracketsEvaluate 2 * (3 + (4 - 1))
Big data processingLarge array split into halvesParallel sum with Fork/Join

Application examples in code

  • GCD (Euclid): gcd(a, b) = gcd(b, a % b) until b == 0. This is also tail recursion.
  • Palindrome: compare the two ends, then recurse on the inner range.
  • Binary search: compare with the middle, then recurse into one half only.
  • Fast power: x^n = (x^(n/2))^2, so only about log2(n) calls are needed.
public class RecursionApps {
    static int gcd(int a, int b) {
        if (b == 0) return a;                       // base case
        return gcd(b, a % b);
    }

    static boolean isPalindrome(String s, int l, int r) {
        if (l >= r) return true;                    // base case
        if (s.charAt(l) != s.charAt(r)) return false;
        return isPalindrome(s, l + 1, r - 1);
    }

    static int binarySearch(int[] a, int key, int lo, int hi) {
        if (lo > hi) return -1;                     // not found
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == key) return mid;
        if (key < a[mid]) return binarySearch(a, key, lo, mid - 1);
        return binarySearch(a, key, mid + 1, hi);
    }

    static long power(long x, int n) {
        if (n == 0) return 1;
        long half = power(x, n / 2);
        return (n % 2 == 0) ? half * half : half * half * x;
    }

    public static void main(String[] args) {
        System.out.println(gcd(48, 18));                          // 6
        System.out.println(isPalindrome("level", 0, 4));          // true
        System.out.println(binarySearch(new int[]{1, 3, 5, 7, 9}, 7, 0, 4)); // 3
        System.out.println(power(2, 30));                         // 1073741824
    }
}

Application: folder size with java.io.File

  • A folder is a tree: its size is the sum of its files plus the size of every sub-folder.
  • The base case is a plain file (or an unreadable folder where listFiles() returns null).
  • In production code you can also use Files.walk(path), which hides the recursion behind a Stream.
import java.io.File;

public class FolderSize {
    static long sizeOf(File f) {
        if (f.isFile()) return f.length();     // base case: a file
        File[] children = f.listFiles();
        if (children == null) return 0;         // unreadable folder
        long total = 0;
        for (File child : children) {
            total += sizeOf(child);              // recurse into each child
        }
        return total;
    }

    public static void main(String[] args) {
        File dir = new File(args.length > 0 ? args[0] : ".");
        System.out.println(dir.getAbsolutePath() + " = " + sizeOf(dir) + " bytes");
    }
}

Differences between recursion and iteration

  • Both repeat work. Choose based on clarity, input depth, and performance.
PointRecursionIteration (loops)
ApproachMethod calls itselfUses for, while, or do-while
TerminationBase caseLoop condition becomes false
MemoryOne stack frame per active callUsually constant extra memory
Failure modeStackOverflowError if too deepInfinite loop if the condition never fails
SpeedCall overhead; can repeat workUsually faster for simple counting
Code sizeShort for trees, Hanoi, backtrackingLonger for nested structures (needs explicit stack)
ReadabilityMatches recursive definitionsMatches step-by-step processes
Best forTrees, graphs, backtracking, divide and conquerLinear scans, counters, very deep inputs

When to use recursion vs a loop

  • Prefer recursion when the data is hierarchical (trees, folders, JSON) or the problem is self-similar (Hanoi, merge sort, backtracking).
  • Prefer a loop for simple 1..n accumulation, array scans, and any input whose depth could reach thousands.
  • Any recursion can be rewritten as a loop with an explicit ArrayDeque stack. That is the standard fix for deep inputs in Java.
L2

Advanced — Recursion

Stack, memoization, and tail calls

  • Naive fib(n) makes about φ^n calls (exponential). Memoize with an array or HashMap, or use a loop, to get O(n). Interviewers expect you to mention this.
  • HotSpot does not perform tail-call optimization. A tail-recursive Java method still uses one stack frame per call.
  • The default thread stack is small (commonly 512 KB to 1 MB). Deep recursion such as fact(100000) or a linked list of a million nodes will overflow.
  • You can create a Thread with a larger stack size (new Thread(null, task, "deep", 64L << 20)), but rewriting as iteration is usually the better fix.
import java.util.Arrays;

public class FibMemo {
    static long[] memo;

    static long fib(int n) {
        if (n <= 1) return n;
        if (memo[n] != -1) return memo[n];      // reuse cached result
        return memo[n] = fib(n - 1) + fib(n - 2);
    }

    public static void main(String[] args) {
        int n = 90;
        memo = new long[n + 1];
        Arrays.fill(memo, -1);
        System.out.println(fib(n));             // 2880067194370816120
    }
}

Direct vs indirect recursion

  • Direct: f calls f. Indirect (mutual): f calls g and g calls f, or a longer cycle.
  • Indirect recursion appears in recursive-descent parsers: expression() calls term(), term() calls factor(), and factor() calls expression() for brackets.
  • The same rules apply: every path needs a base case and progress toward it.
public class EvenOdd {
    static boolean isEven(int n) {
        if (n == 0) return true;
        return isOdd(n - 1);
    }

    static boolean isOdd(int n) {
        if (n == 0) return false;
        return isEven(n - 1);
    }

    public static void main(String[] args) {
        System.out.println(isEven(10));   // true
        System.out.println(isOdd(7));     // true
    }
}

Divide and conquer application: merge sort

  • Divide the array into halves, sort each half recursively, then merge the two sorted halves.
  • Recursion depth is only about log2(n), so it is safe even for millions of elements.
  • Time O(n log n) in every case; extra memory O(n) for the temporary array.
import java.util.Arrays;

public class MergeSort {
    static void sort(int[] a, int lo, int hi) {
        if (lo >= hi) return;                  // base case: 0 or 1 element
        int mid = lo + (hi - lo) / 2;
        sort(a, lo, mid);
        sort(a, mid + 1, hi);
        merge(a, lo, mid, hi);
    }

    static void merge(int[] a, int lo, int mid, int hi) {
        int[] tmp = new int[hi - lo + 1];
        int i = lo, j = mid + 1, k = 0;
        while (i <= mid && j <= hi) tmp[k++] = (a[i] <= a[j]) ? a[i++] : a[j++];
        while (i <= mid) tmp[k++] = a[i++];
        while (j <= hi) tmp[k++] = a[j++];
        System.arraycopy(tmp, 0, a, lo, tmp.length);
    }

    public static void main(String[] args) {
        int[] a = {38, 27, 43, 3, 9, 82, 10};
        sort(a, 0, a.length - 1);
        System.out.println(Arrays.toString(a)); // [3, 9, 10, 27, 38, 43, 82]
    }
}

Backtracking application: subsets and permutations

  • Pattern: choose an option, recurse, undo the choice (backtrack), then try the next option.
  • Real-life analogy: walking a maze. At a dead end you step back to the last junction and try another corridor.
  • Used for N-Queens, Sudoku, subset sum, word search, and generating all combinations.
import java.util.ArrayList;
import java.util.List;

public class Backtracking {
    static void subsets(int[] nums, int i, List<Integer> cur) {
        if (i == nums.length) {                // base case: decided every element
            System.out.println(cur);
            return;
        }
        subsets(nums, i + 1, cur);             // exclude nums[i]
        cur.add(nums[i]);                      // choose
        subsets(nums, i + 1, cur);             // include nums[i]
        cur.remove(cur.size() - 1);            // undo (backtrack)
    }

    static void permute(String prefix, String rest) {
        if (rest.isEmpty()) {
            System.out.println(prefix);
            return;
        }
        for (int i = 0; i < rest.length(); i++) {
            permute(prefix + rest.charAt(i), rest.substring(0, i) + rest.substring(i + 1));
        }
    }

    public static void main(String[] args) {
        subsets(new int[]{1, 2, 3}, 0, new ArrayList<>()); // 8 subsets
        permute("", "ABC");                                 // 6 permutations
    }
}

Tree application: binary tree traversal and height

  • A binary tree node has a left subtree and a right subtree, so tree methods are naturally recursive.
  • Base case is almost always node == null.
  • Height = 1 + max(height(left), height(right)). Count = 1 + count(left) + count(right).
public class TreeRec {
    static class Node {
        int val;
        Node left, right;
        Node(int val) { this.val = val; }
    }

    static void inorder(Node n) {
        if (n == null) return;
        inorder(n.left);
        System.out.print(n.val + " ");
        inorder(n.right);
    }

    static int height(Node n) {
        if (n == null) return 0;
        return 1 + Math.max(height(n.left), height(n.right));
    }

    public static void main(String[] args) {
        Node root = new Node(4);
        root.left = new Node(2);
        root.right = new Node(6);
        root.left.left = new Node(1);
        root.left.right = new Node(3);
        inorder(root);                         // 1 2 3 4 6
        System.out.println();
        System.out.println(height(root));      // 3
    }
}

Parallel application: Fork/Join RecursiveTask

  • java.util.concurrent.RecursiveTask is the JDK built-in way to apply divide and conquer across CPU cores.
  • Split the work until it is small (a threshold), solve small pieces directly, then join the results.
  • Parallel streams use the same Fork/Join pool internally.
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ParallelSum extends RecursiveTask<Long> {
    private static final int THRESHOLD = 10_000;
    private final int[] a;
    private final int lo, hi;

    ParallelSum(int[] a, int lo, int hi) { this.a = a; this.lo = lo; this.hi = hi; }

    @Override
    protected Long compute() {
        if (hi - lo <= THRESHOLD) {            // base case: small enough
            long s = 0;
            for (int i = lo; i < hi; i++) s += a[i];
            return s;
        }
        int mid = (lo + hi) >>> 1;
        ParallelSum left = new ParallelSum(a, lo, mid);
        ParallelSum right = new ParallelSum(a, mid, hi);
        left.fork();                           // run left half asynchronously
        return right.compute() + left.join();
    }

    public static void main(String[] args) {
        int[] data = new int[1_000_000];
        for (int i = 0; i < data.length; i++) data[i] = i % 100;
        System.out.println(ForkJoinPool.commonPool().invoke(new ParallelSum(data, 0, data.length)));
    }
}

Converting recursion to iteration with an explicit stack

  • When input depth can be huge, replace the call stack with your own ArrayDeque.
  • Push the starting item, then loop: pop, process, push children.
  • This is how production code walks very deep trees and graphs without StackOverflowError.
import java.io.File;
import java.util.ArrayDeque;
import java.util.Deque;

public class FolderSizeIterative {
    static long sizeOf(File root) {
        long total = 0;
        Deque<File> stack = new ArrayDeque<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            File f = stack.pop();
            if (f.isFile()) {
                total += f.length();
            } else {
                File[] kids = f.listFiles();
                if (kids != null) for (File k : kids) stack.push(k);
            }
        }
        return total;
    }

    public static void main(String[] args) {
        System.out.println(sizeOf(new File(".")) + " bytes");
    }
}

Recursion safety checklist

  • Write the base case first and test it alone.
  • Make sure every recursive path moves closer to the base (smaller n, narrower range, shorter string, child node).
  • Test n = 0, n = 1, and one medium value with a paper trace.
  • Use long (or BigInteger) for factorial and Fibonacci: int overflows at 13! and fib(47).
  • Add memoization when the call tree repeats sub-problems.
  • If depth may reach thousands, use iteration or an explicit ArrayDeque stack.
  • Never "fix" a StackOverflowError by catching it.
L3

Tricky Interview Points

Q1) What is recursion?

Answer A technique where a method solves a problem by calling itself on a smaller sub-problem until a base case stops the calls.

Q2) What are the base case and the recursive case?

Answer The base case returns a result without another recursive call. The recursive case calls the method again with a smaller input and combines the result.

Q3) What happens if there is no base case?

Answer The calls never stop. Each call adds a stack frame until the JVM throws StackOverflowError.

Q4) What exception does infinite recursion throw? Should you catch it?

Answer java.lang.StackOverflowError, which is an Error, not a checked Exception. Catching it is almost never the right fix; correct the base case or switch to iteration.

Q5) Give some applications of recursion.

Answer Factorial, Fibonacci, GCD, Tower of Hanoi, binary search, merge sort and quick sort, tree traversals, graph DFS, backtracking (N-Queens, Sudoku, maze), permutations and subsets, folder size, JSON/XML tree processing, recursive-descent parsers, flood fill, minimax game AI, and Fork/Join parallel tasks.

Q6) Recursion vs iteration?

Answer Recursion uses method calls and stack memory; iteration uses loops and usually constant memory. Recursion is clearer for trees and backtracking; iteration is safer for deep linear work in Java. Any recursion can be converted to iteration with an explicit stack.

Q7) Does Java optimize tail recursion?

Answer No. HotSpot does not guarantee tail-call optimization, so even tail-recursive methods use one frame per call. Prefer loops for large n.

Q8) What is tail recursion vs head (non-tail) recursion?

Answer In tail recursion the recursive call is the last action, such as return gcd(b, a % b). In non-tail recursion work remains after the call, such as return n * fact(n - 1).

Q9) Direct vs indirect recursion?

Answer Direct: a method calls itself. Indirect (mutual): methods call each other in a cycle, such as isEven calling isOdd and isOdd calling isEven.

Q10) Why is naive recursive Fibonacci slow? How do you fix it?

Answer It recomputes the same sub-problems, giving exponential calls. Fix with memoization (array or HashMap cache), bottom-up DP, or a simple loop, all O(n).

Q11) How many moves does Tower of Hanoi need for n disks?

Answer 2^n - 1 moves. For 3 disks that is 7; for 64 disks it is about 1.8 x 10^19.

Q12) What is backtracking?

Answer A recursive search that makes a choice, recurses, and undoes the choice before trying the next option. Used for N-Queens, Sudoku, subsets, and permutations.

Q13) How do you recurse over a binary tree?

Answer Handle node == null as the base case, then recurse on left and right. Inorder is left, node, right. DFS is naturally recursive; BFS uses a Queue instead.

Q14) Where does the JDK itself use recursion-based design?

Answer Fork/Join (RecursiveTask, RecursiveAction) and parallel streams use divide and conquer. Arrays.sort for objects uses a merge-based TimSort, and Files.walk hides a directory-tree traversal.

Q15) How do you avoid StackOverflowError for very deep inputs?

Answer Convert the recursion to a loop with an explicit ArrayDeque stack, reduce depth with divide and conquer, or as a last resort run the work in a Thread created with a larger stack size.

Q16) What is the space complexity of recursive factorial?

Answer O(n), because n stack frames are active at the deepest point. An iterative loop uses O(1) extra space.

L4

Simple Programs

Factorial and sum of digits

public class BasicRecursion {
    static long fact(int n) {
        if (n <= 1) return 1;
        return n * fact(n - 1);
    }

    static int sumDigits(int n) {
        if (n == 0) return 0;
        return n % 10 + sumDigits(n / 10);
    }

    public static void main(String[] args) {
        System.out.println(fact(10));        // 3628800
        System.out.println(sumDigits(1234)); // 10
    }
}

Fibonacci: naive vs memoized

import java.util.HashMap;
import java.util.Map;

public class FibDemo {
    static long fibNaive(int n) {
        if (n <= 1) return n;
        return fibNaive(n - 1) + fibNaive(n - 2);
    }

    static long fibMemo(int n, Map<Integer, Long> memo) {
        if (n <= 1) return n;
        if (memo.containsKey(n)) return memo.get(n);
        long v = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
        memo.put(n, v);
        return v;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) System.out.print(fibNaive(i) + " "); // 0 1 1 2 3 5 8 13 21 34
        System.out.println();
        System.out.println(fibMemo(50, new HashMap<>()));                  // 12586269025
    }
}

Reverse a string and check palindrome

public class StringRecursion {
    static String reverse(String s) {
        if (s.length() <= 1) return s;
        return reverse(s.substring(1)) + s.charAt(0);
    }

    static boolean isPalindrome(String s) {
        if (s.length() <= 1) return true;
        if (s.charAt(0) != s.charAt(s.length() - 1)) return false;
        return isPalindrome(s.substring(1, s.length() - 1));
    }

    public static void main(String[] args) {
        System.out.println(reverse("recursion"));  // noisrucer
        System.out.println(isPalindrome("madam"));  // true
        System.out.println(isPalindrome("java"));   // false
    }
}

Tower of Hanoi with move count

public class HanoiCount {
    static int moves = 0;

    static void hanoi(int n, char from, char to, char via) {
        if (n == 0) return;
        hanoi(n - 1, from, via, to);
        moves++;
        System.out.println("Move disk " + n + " from " + from + " to " + to);
        hanoi(n - 1, via, to, from);
    }

    public static void main(String[] args) {
        hanoi(3, 'A', 'C', 'B');
        System.out.println("Total moves = " + moves); // 7
    }
}

Recursive binary search

public class RecBinarySearch {
    static int search(int[] a, int key) {
        return search(a, key, 0, a.length - 1);
    }

    private static int search(int[] a, int key, int lo, int hi) {
        if (lo > hi) return -1;
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == key) return mid;
        return key < a[mid] ? search(a, key, lo, mid - 1) : search(a, key, mid + 1, hi);
    }

    public static void main(String[] args) {
        int[] a = {2, 4, 6, 8, 10, 12};
        System.out.println(search(a, 10)); // 4
        System.out.println(search(a, 5));  // -1
    }
}

Application: directory tree printer

import java.io.File;

public class TreePrinter {
    static void print(File f, String indent) {
        System.out.println(indent + (f.isDirectory() ? "[" + f.getName() + "]" : f.getName()));
        if (!f.isDirectory()) return;          // base case: a file
        File[] kids = f.listFiles();
        if (kids == null) return;
        for (File k : kids) print(k, indent + "    ");
    }

    public static void main(String[] args) {
        print(new File(args.length > 0 ? args[0] : "."), "");
    }
}

Application: N-Queens (backtracking)

public class NQueens {
    static int solutions = 0;

    static boolean safe(int[] cols, int row, int col) {
        for (int r = 0; r < row; r++) {
            if (cols[r] == col || Math.abs(cols[r] - col) == row - r) return false;
        }
        return true;
    }

    static void place(int[] cols, int row) {
        if (row == cols.length) {              // base case: all queens placed
            solutions++;
            return;
        }
        for (int c = 0; c < cols.length; c++) {
            if (safe(cols, row, c)) {
                cols[row] = c;                 // choose
                place(cols, row + 1);          // recurse
            }                                  // undo happens by overwriting cols[row]
        }
    }

    public static void main(String[] args) {
        place(new int[8], 0);
        System.out.println("8-Queens solutions: " + solutions); // 92
    }
}

Application: flood fill (paint bucket)

public class FloodFill {
    static void fill(char[][] g, int r, int c, char target, char repl) {
        if (r < 0 || c < 0 || r >= g.length || c >= g[0].length) return;
        if (g[r][c] != target) return;
        g[r][c] = repl;
        fill(g, r + 1, c, target, repl);
        fill(g, r - 1, c, target, repl);
        fill(g, r, c + 1, target, repl);
        fill(g, r, c - 1, target, repl);
    }

    public static void main(String[] args) {
        char[][] g = {
            "..##".toCharArray(),
            ".#..".toCharArray(),
            "....".toCharArray()
        };
        fill(g, 0, 0, '.', '*');
        for (char[] row : g) System.out.println(new String(row));
        // **##
        // *#**
        // ****
    }
}
L5

Problem Solving Tricks

  • Write the base case first, then the recursive step that moves toward it.
  • Ask "what is the smallest version of this problem?" — that is your base case.
  • Trust the recursion: assume the smaller call already works, and only write how to combine its answer.
  • Print a depth-indented trace while learning: System.out.println(" ".repeat(depth) + n);.
  • If you see the same arguments twice in a call tree, add memoization.
  • Use a private helper with extra parameters (lo, hi, index, depth) and keep the public method simple.
  • For trees, always ask: can the root be null? Handle node == null as the base case.
  • For backtracking, remember three steps: choose, recurse, undo.
  • Use long or BigInteger for factorial and Fibonacci; int overflows at 13! and fib(47).
  • If depth might exceed a few thousand, rewrite with an ArrayDeque stack before it fails in production.
L6

Practice Programs List

  1. Write recursive sum(int[] a, int i) that sums the array from index i to the end.
  2. Find the maximum element of an array recursively.
  3. Count the number of digits in a number recursively.
  4. Compute GCD and LCM with Euclid recursion.
  5. Compute nCr using nCr = (n-1)C(r-1) + (n-1)Cr, then add memoization.
  6. Convert a decimal number to binary using recursion.
  7. Print all permutations of a string without duplicates (input "AAB").
  8. Generate all subsets of {1, 2, 3, 4} and print only those whose sum is 5.
  9. Solve a maze in a char[][] grid with backtracking and mark the path.
  10. Write recursive inorder, preorder, and postorder traversals for a binary tree.
  11. Write a method that counts all .java files under a folder using java.io.File recursion.
  12. Evaluate a simple expression like 2 * (3 + 4) with a recursive-descent parser.
  13. Rewrite the recursive folder-size program iteratively using ArrayDeque.
  14. Draw the call tree for fib(5) on paper, count the calls, then memoize and count again.