Teaching Kids Programming: Videos on Data Structures and Algorithms
Recursive Tree in Python using Turtle Graphics
A tree is self-recursive just like the data structure binary tree where the left and right are recursively defined.
Here is how we define a binary tree to hold data:
1 2 3 4 5 | class TreeNode(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right |
class TreeNode(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right
With the turtle graphics library aka import turtle, we draw the trunk (walk N steps), turn left 30 degrees and then draw a left sub tree with size smaller e.g. 60%*N. Then we turn 60 degree to draw the right sub tree. Then we turn left 30 degree and walk backwards N steps so that the turtle restores to the begining.
The subtrees will be recursively drawn until N is falling below a threshold e.g. 10 steps.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | from turtle import * reset() color("green") speed(-1) seth(90) def tree(size): if size < 10: return fd(size) lt(30) tree(size * 0.6) rt(60) tree(size * 0.6) lt(30) bk(size) tree(100) |
from turtle import * reset() color("green") speed(-1) seth(90) def tree(size): if size < 10: return fd(size) lt(30) tree(size * 0.6) rt(60) tree(size * 0.6) lt(30) bk(size) tree(100)
See also: Bug-fixes for PHP Online Logo Interpreter
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
363 wordsloading...
Last Post: Teaching Kids Programming - Is Subsequence Algorithm via Recursion (Greedy)
Next Post: Teaching Kids Programming - Delete the Middle Node of a Linked List (Fast and Slow Pointer)