Recursive Tree
In this lab, you will create a tree-drawing program that uses recursion to draw the branches by drawing smaller and smaller trees.
On this page, you will explore nesting code for trees inside code for trees.
The branching pattern on many plants has fractal structure: the smaller parts are like miniature copies of the whole plant.
A fractal is an infinite repeating pattern made up of copies (or slight variations) of the same shape. In this picture, the green branch is (essentially) the same shape as the entire picture.

- "U7L1-Tree"
-
Build the first level.
-
Build a
tree 1
block. It looks simple, but things will get more complicated soon.
-
Point the sprite up, put the pen down, and run
. You should get a result like this:
Where does your sprite start? In what direction is it facing? Where does it stop?
-
Build a
-
UsingBuild a
tree 1
to draw the branches intree 2
is using abstraction.tree 2
block that usestree 1
as its branches.
Describe exactly the position and direction of the sprite when the first
tree 1
stops running. Why is that essential fortree 2
to work?
State transparency means putting everything back exactly as it was when you started. It is especially important when blocks depend on other blocks. Usually, this means returning the sprite to the same position and direction and returning the pen to the same color and size.
- Make a
tree 3
block that uses thetree 2
block as branches.Right-click (or control-click on a Mac) a block to "duplicate" or "relabel" blocks to make these tasks much faster. Click for an example.Needs better alt/title text. --MF, 6/18/20 - Make a
tree 4
block that uses thetree 3
block as branches. -
If you like, make a
tree 5
block that uses thetree 4
block. Runningshould produce a result like this.
These blocks all look essentially the same except that tree 5
uses tree 4
, while tree 4
uses tree 3
, and tree 3
uses tree 2
, etc. So it makes sense to wonder if we can replace all these blocks with a single tree
block by using a variable for the number that changes.
Using a procedure inside of itself is called recursion.
-
This is the general idea for the recursive version.
What are the differences between this recursive tree script and the code for
tree 2
andtree 3
, and why are these differences needed?
-
Here is what happens if you run
tree, level: 9 size: 50
.
It doesn't work. Try to debug the script. Consider building the code and running it yourself.What's going wrong?