python二叉树画法
时间: 2023-11-18 12:57:21 浏览: 100
二叉树的画法
Python中可以使用turtle库来画二叉树,具体实现方法如下:
```python
import turtle
# 定义二叉树节点类
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# 递归画二叉树
def draw_tree(root, x, y, gap):
if not root:
return
# 画节点
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.circle(20)
turtle.penup()
turtle.goto(x, y-20)
turtle.write(root.val, align="center", font=("Arial", 12, "normal"))
# 画左子树
if root.left:
x_left = x - gap
y_left = y - 50
turtle.goto(x_left, y_left)
turtle.pendown()
turtle.goto(x, y-20)
draw_tree(root.left, x_left, y_left, gap/2)
# 画右子树
if root.right:
x_right = x + gap
y_right = y - 50
turtle.goto(x_right, y_right)
turtle.pendown()
turtle.goto(x, y-20)
draw_tree(root.right, x_right, y_right, gap/2)
# 测试
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
turtle.speed(0)
draw_tree(root, 0, 200, 200)
turtle.hideturtle()
turtle.done()
```
阅读全文