Python用turtle可视化二叉树中序遍历
时间: 2023-06-12 13:05:37 浏览: 181
基于python的爱心绘制源码
可以使用Python中的turtle库来可视化二叉树的中序遍历。具体实现步骤如下:
1. 首先,导入turtle库和random库,并定义一个Node类表示二叉树的节点。
```python
import turtle
import random
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
```
2. 定义一个函数draw_node,用于在窗口上绘制一个二叉树节点。该函数接受四个参数:x、y表示节点的坐标,size表示节点的大小,color表示节点的颜色。
```python
def draw_node(x, y, size, color):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.fillcolor(color)
turtle.begin_fill()
turtle.circle(size)
turtle.end_fill()
turtle.penup()
turtle.goto(x, y - size * 1.2)
turtle.write(str(value), align="center", font=("Arial", 12, "normal"))
```
3. 定义一个函数inorder,用于进行二叉树的中序遍历,并在遍历的过程中绘制节点。该函数接受两个参数:root表示二叉树的根节点,x表示根节点的横坐标。
```python
def inorder(root, x):
if root is not None:
inorder(root.left, x - 50)
draw_node(x, 0, 20, "blue")
turtle.penup()
turtle.goto(x, 50)
turtle.pendown()
turtle.goto(x, 20)
turtle.penup()
turtle.goto(x - 20, -20)
turtle.write(str(root.value), align="center", font=("Arial", 12, "normal"))
inorder(root.right, x + 50)
```
4. 最后,生成一个随机的二叉树,并调用inorder函数进行中序遍历。设置turtle窗口的大小,并隐藏turtle的箭头。
```python
root = Node(random.randint(0, 100))
for i in range(20):
node = Node(random.randint(0, 100))
current = root
while True:
if node.value < current.value:
if current.left is None:
current.left = node
break
else:
current = current.left
else:
if current.right is None:
current.right = node
break
else:
current = current.right
turtle.setup(width=800, height=600)
turtle.hideturtle()
inorder(root, 400)
```
完整代码如下:
```python
import turtle
import random
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def draw_node(x, y, size, color):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.fillcolor(color)
turtle.begin_fill()
turtle.circle(size)
turtle.end_fill()
turtle.penup()
turtle.goto(x, y - size * 1.2)
turtle.write(str(value), align="center", font=("Arial", 12, "normal"))
def inorder(root, x):
if root is not None:
inorder(root.left, x - 50)
draw_node(x, 0, 20, "blue")
turtle.penup()
turtle.goto(x, 50)
turtle.pendown()
turtle.goto(x, 20)
turtle.penup()
turtle.goto(x - 20, -20)
turtle.write(str(root.value), align="center", font=("Arial", 12, "normal"))
inorder(root.right, x + 50)
root = Node(random.randint(0, 100))
for i in range(20):
node = Node(random.randint(0, 100))
current = root
while True:
if node.value < current.value:
if current.left is None:
current.left = node
break
else:
current = current.left
else:
if current.right is None:
current.right = node
break
else:
current = current.right
turtle.setup(width=800, height=600)
turtle.hideturtle()
inorder(root, 400)
```
阅读全文