1. Sierpinski Triangle Sierpinski Triangle The Sierpinski Triangle is a pattern that exhibits self-similarity. We have seen at least two ways of generating this pattern (image from Wikipedia): depth=0 depth=1 depth=2 depth=3 depth=4 Now that we have recursion as a problem solving technique we can generate the true pattern by calculating the true coordinates of each triangle in the subdivision.
 Goal: Write a recursive method drawNestedTris(x1, y1, x2, y2, x3, y3, depth) that generates a pattern of nested triangles, i.e. a Sierpinski Triangle with initial vertices (x1,y1), (x2,y2), (x3,y3). The pattern is drawn up to the given depth. The meaning of depth is the number of distinct sizes of yellow triangles (see above).
From the above images one can see the recursive process of constructing the pattern:

To draw nested triangles inside a given triangle T:

1. Calculate the midpoints of the sides of T. This
   creates four regions inside T: T0, T1, T2, T3

2. Draw the triangle T0 that connects the midpoints.

4. Draw nested triangles inside T1, T2, T3 (similar)
   of depth one less than original.        (smaller)

          x3,y3 
           / \
          /   \ 
         / T3  \
x13,y13 /______ \x23,y23
       /\ \ \ \/ \
      /  \ \ \/   \
     / T1 \ \/ T2  \
    /______\/_______\
x1,y1    x12,y12   x2,y2
Here is the Java code that generates the pattern:

class RecursionApp
{
    // I draw many small triangles inside the given triangle
    void drawNestedTris( double x1, double y1, double x2, double y2, double x3, double y3, int depth )
    {
        if ( depth == 0 ) // easy case, no subdivision, just the triangle
        {
            canvas.drawTriangle( x1, y1, x2, y2, x3, y3, "red" );
        }
        else
        {
            // calculate the mid points of the sides
            double x12 = (x1 + x2) / 2;
            double y12 = (y1 + y2) / 2;
            
            double x13 = (x1 + x3) / 2;
            double y13 = (y1 + y3) / 2;
            
            double x23 = (x2 + x3) / 2;
            double y23 = (y2 + y3) / 2;

            // draw the middle triangle
            canvas.drawTriangle( x12, y12, x23, y23, x13, y13, "yellow" );
            canvas.sleep( 1 );

            // recursively generate the pattern within the remaining pieces            
            drawNestedTris( x1, y1, x12, y12, x13, y13, depth-1 );   // T1, lower-left piece
            drawNestedTris( x12, y12, x2, y2, x23, y23, depth-1 );   // T2, lower-right piece
            drawNestedTris( x13, y13, x23, y23, x3, y3, depth-1 );   // T3, top piece
        }
    }

    public void run()
    {
        // draw the Sierpinski pattern within a main triangle 
        // with verts  x1  y1   x2   y2   x3   y3  depth

        drawNestedTris( 0, 500, 500, 500, 250, 0,    6 );
    }
}