利用python自帶的turtle庫來畫二叉樹
1.第一部分
二叉樹的畫法主要是利用遞歸的方法來畫,其中有用的深度優先算法的思想。
步驟也不復雜,先畫左邊,然後畫右邊。
2.代碼
import turtle
def draw(strength):
if strength>0:
turtle.fd(strength)
turtle.rt(20) #右轉20°
draw(strength-5) #每一節樹枝比前一節短5
turtle.lt(40) #之前右轉了20°,所以這裏要左轉40°。
draw(strength-5)
if(strength<25):
turtle.pencolor("green") #如果樹枝的長度小於25,那麼就設置畫筆的顏色爲綠色
turtle.rt(20)
turtle.backward(strength) #放回
turtle.pencolor("black")
if main():
strenght = 80 #設置樹的長度
turtle.penup()
turtle.goto(-50,-100) #向下移動畫筆
turtle.pendown()
turtle.letf(90) #開始畫筆的方向爲朝右,轉到向上
draw(strength)
turtle.exitonclick() #設置畫完後不立即結束程序
程序運行效果圖,畫了一大半,還要一小半沒畫出來,
Thank for your reading!