Recursion repetition without loops
Recursion definition solving a problem in terms of a smaller version of itself form of a recursive solution: base case(s) recursive case(s)
Recursion examples for IntNode class find maximum data value in list int maxValue; if (head != null) maxValue = head.maxData(); head maxData
Recursion examples for IntNode class public class IntNode { private int data; private IntNode link; public IntNode(int d, IntNode n) { data = d; link = n; }
Max value in linked list public int maxData () // non-recursive version { int max = data; IntNode cursor = link; while (cursor != null) { if (cursor.data > max) max = cursor.data; cursor = cursor.link; } return max; }
Max value in linked list public int maxData () // recursive version { if (link == null) return data; int maxOfRest = link.maxData(); return Math.max(maxOfRest, data); }
Sum of values in linked list public int sumData () // non-recursive version { int sum = data; IntNode cursor = link; while (cursor != null) { sum += cursor.data; cursor = cursor.link; } return sum; }
Sum of values in linked list public int sumData () // recursive version { if (link == null) return data; return data + link.sumData(); }
Other examples: search for a value in list two base cases count occurrences of a value in a list make a reverse copy of a list
a recursive method wrapper // a static method public static IntNode reverseList(IntNode head) { if (head == null) return null; return head.reverse(null); }
make a reverse copy of a list public IntNode reverse(IntNode prefix) { IntNode copyThis = new IntNode(data, prefix); if (link == null) // no more nodes return copyThis; return link.reverse(copyThis); }
Other uses of recursive processing directory traversals % ls -R puzzle solutions towers of Hanoi