CS 100: Lecture L18

April 1

| Back to Lecture Index |


// A graphics recursion to illustrate divide and conquer.


import java.io.*;
import java.awt.*;

public class ShowTree extends Frame
{
    // Place constants here
    
    // Draws a dot at the "root" (h,v). 
    // If L > 9 then it draws dots at the "leaves" (h-L,v-L) and (h+L,v-L) and
    // connects them to the root. It then repeats the process at each leaf with L replaced
    // by L/2.
    public static void drawTree(Graphics g, int h, int v, int L)
    {
       int r;
       if (L<=8)
       {
          g.setColor(Color.red);
          g.fillOval(h-4,v-4,8,8);
          return;
       }
       else
       {
          
          g.setColor(Color.yellow);
          g.drawLine(h,v,h-L,v-L); 
          g.drawLine(h,v,h+L,v-L); 
          
          g.setColor(Color.blue);
          r = L/3;
          g.fillOval(h-r,v-r,2*r,2*r);
         
         
          drawTree(g,h-L,v-L,L/2);
          drawTree(g,h+L,v-L,L/2);
       }
    }
    
	public void paint(Graphics g)
	{
	    g.setColor(Color.black);
	    g.fillRect(0,0,1000,1000);
	    drawTree(g,500,500,200);
	
	}
	
}

public class L18
{
	public static void main(String args[])
	{
		ShowTree d = new ShowTree();
		d.resize(1000,800);                    
		d.move(0,75);
		d.setTitle("A Tree");                
		d.show();
		d.toFront();
	}
}