使用python turtle将二叉树画为图形

结果

在这里插入图片描述

存在问题

我把路径都设定为固定长度,所以不能满足所有的二叉树,会出现重合问题,看图
在这里插入图片描述

源码

from turtle import *
import math


# 一些常数用于树构建时turtle的位置控制()
# POSITION[n]代表深度为n节点,画子节点的时候,俩节点连线与水平的距离
POSITION = [0, 30, 30, 30, 30]
# DISTANCE[n]代表深度为n节点与子节点连线长度
DISTANCE = [0, 150, 150, 150, 150, 150]
# XDISTANCE[n] XDISTANCE[n] 代表从双亲节点到子节点的x坐标和y坐标的改变量
XDISTANCE = [0, 75 * math.sqrt(3), 75 * math.sqrt(3), 75 * math.sqrt(3),
             75 * math.sqrt(3), 75 * math.sqrt(3)]
YDISTANCE = [0, 55, 55, 55, 55, 55]
delay(0)


def paintTree(root, pos, n):
    """
    二叉树使用turtle画图
    """
    # 1.移动到当前节点所需要的的位置
    penup()
    goto(pos[0], pos[1])
    pendown()
    if root.flag == 0:
        # 点的值
        seth(0)
        write(root.val, font=("宋体", 20, "normal"))
        # 画圈
        circle(20)
        # 去当前圆圆心
        penup()
        seth(90)
        forward(20)
        pendown()
        # 更新flag
        root.flag = 1
    if root.lchild is not None:
        seth(180 + POSITION[n])
        # 跳出圆圈
        penup()
        forward(20)
        pendown()
        # 前往下一个节点
        forward(DISTANCE[n]-40)
        paintTree(root.lchild, [pos[0] - XDISTANCE[n], pos[1] - YDISTANCE[n]], n+1)
        # 返回这一层,画笔也要改变位置
        penup()
        goto(pos[0], pos[1] + 20)
        pendown()
        # 没有画过的点
    if root.rchild is not None:
        seth(0 - POSITION[n])
        # 跳出圆圈
        penup()
        forward(20)
        pendown()
        # 前往下一个节点
        forward(DISTANCE[n]-40)
        paintTree(root.rchild, [pos[0] + XDISTANCE[n], pos[1] - YDISTANCE[n]], n+1)
        # 返回这一层,画笔也要改变位置
        penup()
        goto(pos[0], pos[1] + 20)
        pendown()


class BinaryTree:
    def __init__(self, val, lchild=None, rchild=None):
        self.val = val
        self.rchild = rchild
        self.lchild = lchild
        self.flag = 0           # 在画turtle时标志当前节点是否已经被画过了


def createBinaryTree(root, vals):
    if len(vals) == 0:
        return root
    if vals[0] != "#":
        root = BinaryTree(vals[0])
        vals.pop(0)
        root.lchild = createBinaryTree(root.lchild, vals)
        root.rchild = createBinaryTree(root.rchild, vals)
        return root
    else:
        root = None
        vals.pop(0)
        return root


if __name__ == "__main__":
    vals = list("abdf###e##c#g##")  # 树的先序遍历结果("#"代表当前为None)
    root = None
    root = createBinaryTree(root, vals)
    paintTree(root, [0, 200], 1)
    done()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值