python实现二叉树的遍历并可视化
时间: 2023-09-08 19:08:27 浏览: 210
要实现二叉树的遍历并可视化,可以使用Python中的Tkinter库来实现图形化界面,使用递归来实现二叉树的遍历。具体实现步骤如下:
1. 导入Tkinter库和random库
```python
import tkinter as tk
import random
```
2. 定义二叉树节点类
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
```
3. 定义二叉树类
```python
class BinaryTree:
def __init__(self):
self.root = None
```
4. 实现二叉树的插入方法
```python
def insert(self, val):
node = TreeNode(val)
if not self.root:
self.root = node
else:
q = [self.root]
while q:
curr = q.pop(0)
if not curr.left:
curr.left = node
break
elif not curr.right:
curr.right = node
break
else:
q.append(curr.left)
q.append(curr.right)
```
5. 实现二叉树的前序遍历、中序遍历和后序遍历方法
```python
def preorderTraversal(self, node, canvas, x, y, gap):
if node:
canvas.create_oval(x-10, y-10, x+10, y+10, fill='white')
canvas.create_text(x, y, text=str(node.val))
if node.left:
canvas.create_line(x, y, x-gap, y+gap)
self.preorderTraversal(node.left, canvas, x-gap, y+gap, gap/2)
if node.right:
canvas.create_line(x, y, x+gap, y+gap)
self.preorderTraversal(node.right, canvas, x+gap, y+gap, gap/2)
def inorderTraversal(self, node, canvas, x, y, gap):
if node:
if node.left:
self.inorderTraversal(node.left, canvas, x-gap, y+gap, gap/2)
canvas.create_line(x-gap, y+gap, x, y)
canvas.create_oval(x-10, y-10, x+10, y+10, fill='white')
canvas.create_text(x, y, text=str(node.val))
if node.right:
canvas.create_line(x, y, x+gap, y+gap)
self.inorderTraversal(node.right, canvas, x+gap, y+gap, gap/2)
def postorderTraversal(self, node, canvas, x, y, gap):
if node:
if node.left:
self.postorderTraversal(node.left, canvas, x-gap, y+gap, gap/2)
if node.right:
self.postorderTraversal(node.right, canvas, x+gap, y+gap, gap/2)
canvas.create_oval(x-10, y-10, x+10, y+10, fill='white')
canvas.create_text(x, y, text=str(node.val))
if node.left:
canvas.create_line(x, y, x-gap, y+gap)
if node.right:
canvas.create_line(x, y, x+gap, y+gap)
```
6. 实现图形化界面
```python
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.geometry('800x600')
self.master.title('Binary Tree Visualization')
self.master.resizable(False, False)
self.pack()
self.create_widgets()
def create_widgets(self):
self.canvas = tk.Canvas(self, width=800, height=600, bg='black')
self.canvas.pack()
self.tree = BinaryTree()
for i in range(10):
self.tree.insert(random.randint(1, 100))
self.tree.preorderTraversal(self.tree.root, self.canvas, 400, 50, 200)
```
7. 运行程序
```python
root = tk.Tk()
app = Application(master=root)
app.mainloop()
```
完整代码如下:
阅读全文