龙空技术网

用python画一棵二叉树(附源码有注释)

程序员玩乐器 221

前言:

现在兄弟们对“python建立二叉树”大约比较看重,小伙伴们都想要分析一些“python建立二叉树”的相关知识。那么小编同时在网摘上汇集了一些关于“python建立二叉树””的相关文章,希望小伙伴们能喜欢,咱们一起来学习一下吧!

更换封面

视频尚未发布,暂时无法播放

from turtle import *import turtleimport timeimport numpyclass Tree: def __init__(self): turtle.colormode(255) turtle.speed(0) turtle.setup(500,500) turtle.pensize(2) self.branchAngle = 60  # 画叶子 def drawLeaf(self,fatherAngle,fatherEnd): turtle.pencolor((0,255,0)) turtle.fillcolor((255, 0, 0)) turtle.penup() turtle.goto(fatherEnd['x'], fatherEnd['y']) turtle.setheading(0) turtle.left(fatherAngle) turtle.right(90) turtle.pendown() turtle.begin_fill() turtle.circle(10) turtle.end_fill() # 画两根树枝 # fatherAngle 父树枝的角度 # fatherLength 父树枝的长度 # fatherEnd 父树枝的终点的坐标 def drawBranch(self,fatherAngle,fatherLength ,fatherEnd ): turtle.pencolor((0, 0, 0))  #画左分枝 turtle.penup() turtle.goto( fatherEnd['x'],fatherEnd['y'] ) turtle.setheading(0) turtle.left(fatherAngle) turtle.left(self.branchAngle/2) turtle.pendown() turtle.forward(fatherLength*0.8) # 画完左分枝,将左分枝数据暂时存到变量 tmp0 = { 'angle': fatherAngle + self.branchAngle/2, # 绝对方向在父树枝的基础上增加分枝角度的一半 'length': fatherLength*0.8, # 长度是父树枝长度的 80% 'point': {'x':turtle.pos()[0],'y':turtle.pos()[1]} } # 画右分枝 turtle.penup() turtle.goto(fatherEnd['x'], fatherEnd['y']) turtle.setheading(0) turtle.left(fatherAngle) turtle.right(self.branchAngle / 2) turtle.pendown() turtle.forward(fatherLength * 0.8) # 画完右分枝,将右分枝数据暂时存到变量 tmp1 = { 'angle': fatherAngle - self.branchAngle / 2, # 绝对方向在父树枝的基础上增加分枝角度的一半 'length': fatherLength * 0.8, # 长度是父树枝长度的 80% 'point': {'x':turtle.pos()[0],'y':turtle.pos()[1]} } #继续处理左分枝 if tmp0['length']>50: # 如果树枝长度大于50,递归调用继续画分枝 self.drawBranch( tmp0['angle'], tmp0['length'],tmp0['point'] ) else: #否则就画叶子 self.drawLeaf( tmp0['angle'],tmp0['point'] )  #继续处理右分枝 if tmp1['length']>50: # 如果树枝长度大于50,递归调用继续画分枝 self.drawBranch( tmp1['angle'], tmp1['length'],tmp1['point'] ) else: #否则就画叶子 self.drawLeaf(tmp1['angle'], tmp1['point'])if __name__=='__main__': Tree().drawBranch(90,120,{'x':0,"y":-200}) #给一个父树枝,就可以开始画了,这个父树枝是不画的 turtle.mainloop()

标签: #python建立二叉树