Chapter 17

Recursion


Chapter Goals

Triangle Numbers

[]
[] []
[] [] []

Outline of Triangle Class

public class Triangle
{
    public Triangle(int aWidth)
    {
       width = aWidth;
    }
    public int getArea()
    {
       ...
    }
    private int width;
} 

Handling Triangle of Width 1

public int getArea()
{
    if (width == 1) return 1;
}

Handling General Case

[]
[] []
[] [] []

[] [] [] []

Computing the area of a triangle with width 4

Recursion

File Triangle.java

TriangleTest.java

Permutations of a String

Public Interface of PermutationGenerator

class PermutationGenerator
{
    public PermutationGenerator(String s) { . . . }
    public String nextPermutation() {. . . }
    public boolean hasMorePermutations() { . . . }
}

File PermutationGeneratorTest.java

To Generate All Permutations

Handling the Special Case

When the tail generator runs out of permutations, we need to:

File PermutationGenerator.java

Recursive Helper Method

public boolean isPalindrome(int start int end)
{
   //separate case for substrings of length 0 or 1
   if (start>=end) return true;

   //get first and last character, converted to lowercase
   char first = Character.toLowerCase(text.charAt(start));
   char last = Character.toLowerCase(text.charAt(end));

   if ((Character.isLetter(first) && Character.isLetter(last))
   {
      if (first == last)
      {
         //test substring that doesn't contain the matching letters
         return isPalindrome(start +1, end -1);
      }
      else
         return false;
   }
   else if (!Character.isLetter(last))
   {
      //test substring that doesn't contain last character
      return isPalindrome(start, end -1);
   }
   else
   {
      //test substring that doesn't contain first character
      return isPalindrome(start + 1, end);
}
   

Using Mutual Recursion

Problem: to compute the value of arithmetic expressions such as

3 + 4 * 5
(3 + 4) * 5
1 - (2 - (3 - (4 - 5)))

Syntax Diagram for Evaluating and Expression

Syntax Diagram

Syntax Tree for Two Expressions

Syntax Tree

Mutually Recursive Methods

File Evaluator.java

File ExpressionTokenizer.java

File EvaluatorTest.java

Fibonacci Sequence

The Efficiency of Recursion

File FibTest.java

Call Pattern of the Recursive fib Method

Call Pattern of Recursive fib Method

File FibTrace.java

File FibLoop.java