编写一个程序显示递归树Python,运用tkinter
时间: 2024-04-07 22:21:44 浏览: 155
python 实现递归输出
以下是一个简单的示例程序,可以用递归方式显示二叉树:
```python
import tkinter as tk
class BinaryTree:
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None
def insert_left(self, value):
if self.left_child is None:
self.left_child = BinaryTree(value)
else:
new_node = BinaryTree(value)
new_node.left_child = self.left_child
self.left_child = new_node
def insert_right(self, value):
if self.right_child is None:
self.right_child = BinaryTree(value)
else:
new_node = BinaryTree(value)
new_node.right_child = self.right_child
self.right_child = new_node
def draw_tree(canvas, node, x, y, x_offset, y_offset):
if node is None:
return
# Draw node
canvas.create_oval(x-10, y-10, x+10, y+10, fill='blue')
canvas.create_text(x, y, text=node.value)
# Draw left child
draw_tree(canvas, node.left_child, x-x_offset, y+y_offset, x_offset/2, y_offset)
# Draw right child
draw_tree(canvas, node.right_child, x+x_offset, y+y_offset, x_offset/2, y_offset)
if __name__ == '__main__':
# Create binary tree
tree = BinaryTree('A')
tree.insert_left('B')
tree.insert_right('C')
tree.left_child.insert_left('D')
tree.left_child.insert_right('E')
tree.right_child.insert_left('F')
tree.right_child.insert_right('G')
# Create canvas
root = tk.Tk()
canvas = tk.Canvas(root, width=600, height=400)
canvas.pack()
# Draw tree
draw_tree(canvas, tree, 300, 50, 200, 50)
tk.mainloop()
```
运行程序后,将会显示一个递归树:
![递归树](https://i.imgur.com/tj9sZiJ.png)
阅读全文