用python写一个二叉树
时间: 2023-07-01 15:09:18 浏览: 72
python 二叉树
下面是一个简单的二叉树的Python实现:
```python
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class BinaryTree:
def __init__(self, root):
self.root = Node(root)
def print_tree(self, traversal_type):
if traversal_type == "preorder":
return self.preorder_print(tree.root, "")
elif traversal_type == "inorder":
return self.inorder_print(tree.root, "")
elif traversal_type == "postorder":
return self.postorder_print(tree.root, "")
def preorder_print(self, start, traversal):
if start:
traversal += (str(start.value) + "-")
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
def inorder_print(self, start, traversal):
if start:
traversal = self.inorder_print(start.left, traversal)
traversal += (str(start.value) + "-")
traversal = self.inorder_print(start.right, traversal)
return traversal
def postorder_print(self, start, traversal):
if start:
traversal = self.postorder_print(start.left, traversal)
traversal = self.postorder_print(start.right, traversal)
traversal += (str(start.value) + "-")
return traversal
# Create a binary tree with root node as 1
tree = BinaryTree(1)
# Add nodes to the binary tree
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
tree.root.right.left = Node(6)
tree.root.right.right = Node(7)
# Print the binary tree in different traversal orders
print(tree.print_tree("preorder"))
print(tree.print_tree("inorder"))
print(tree.print_tree("postorder"))
```
输出:
```
1-2-4-5-3-6-7-
4-2-5-1-6-3-7-
4-5-2-6-7-3-1-
```
这里实现了一个简单的二叉树,并且提供了三种不同的遍历方式:前序遍历、中序遍历和后序遍历。可以根据需要进行选择。
阅读全文