I am trying to draw a tree using recursion. The tree needs to look like this:
A short summary of how I'm supposed to do it:
- The trunk of the tree has length of
length
and widthwidth
- The trunk splits into two branches
- The left one has the 3/4 of the trunk length and the right one 2/3 of the trunk length
- Left branch width is 3/4 of the trunk width and the right branch width is 1/2 of trunk width
- The parameters that we receive are length, min_length, width, alpha (all doubles)
- The branches grow until the branches are longer than the min_length
Here's how I tackled the problem. I wanted to just draw the trunk, left branch and right branch. I managed to do this, with the following function:
public void drawTree(double length, double min_length, double width, double alpha) {
//Draws the trunk of the tree
StdDraw.setPenRadius(width);
StdDraw.line(250, 150, 250, 150+length);
//Left branch
double hypotenuse = (3.0/4.0)*length;
double opposite = Math.sin(alpha) * hypotenuse;
double adjacent = Math.sqrt(Math.pow(hypotenuse, 2)-Math.pow(opposite, 2));
StdDraw.setPenRadius(width*3.0/4.0);
StdDraw.line(250,150+length,250-adjacent,150+length+opposite);
//Right branch
double hypotenuse2 = (2.0/3.0)*length;
double opposite2 = Math.sin(alpha) * hypotenuse2;
double adjacent2 = Math.sqrt(Math.pow(hypotenuse2, 2)-Math.pow(opposite2, 2));
StdDraw.setPenRadius(width*1.0/2.0);
StdDraw.line(250,150+length,250+adjacent2,150+length+opposite2);
}
This is the output and it is just as I wanted it to be:
I thought the rest would be easy, but I haven't made any progress in the last 3 hours :/. I included the if statement for the stopping condition. But I don't have an idea about the recursive part. I've tried this:
if (length > min_length) {
//Left branch
double hypotenuse = (3.0/4.0)*length;
double opposite = Math.sin(alpha) * hypotenuse;
double adjacent = Math.sqrt(Math.pow(hypotenuse, 2)-Math.pow(opposite, 2));
StdDraw.setPenRadius(width*3.0/4.0);
StdDraw.line(250,150+length,250-adjacent,150+length+opposite);
//Right branch
double hypotenuse2 = (2.0/3.0)*length;
double opposite2 = Math.sin(alpha) * hypotenuse2;
double adjacent2 = Math.sqrt(Math.pow(hypotenuse2, 2)-Math.pow(opposite2, 2));
StdDraw.setPenRadius(width*1.0/2.0);
StdDraw.line(250,150+length,250+adjacent2,150+length+opposite2);
//My first attempt
drawTree(hypotenuse*hypotenuse, min_length, width, alpha);
drawTree(hypotenuse2*hypotenuse2, min_length, width, alpha);
//My second attempt
drawTree(hypotenuse, min_length, width, alpha);
drawTree(hypotenuse2, min_length, width, alpha);
}
I understand simple recursion like factorials, palindrome, etc, but I'm stuck on this one and I'd appreciate any help.