自定义类实现二叉树,python完整代码
时间: 2024-06-21 07:01:10 浏览: 329
在Python中,我们可以自定义一个类来实现二叉树。以下是一个简单的二叉树类,包括节点的创建、插入和基本的遍历(前序、中序和后序):
```python
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, value):
if not self.root:
self.root = Node(value)
else:
self._insert(self.root, value)
def _insert(self, node, value):
if value < node.value:
if node.left is None:
node.left = Node(value)
else:
self._insert(node.left, value)
else:
if node.right is None:
node.right = Node(value)
else:
self._insert(node.right, value)
# 前序遍历 (根-左-右)
def pre_order_traversal(self, node=None):
if node is None:
node = self.root
if node:
print(node.value, end=" -> ")
self.pre_order_traversal(node.left)
self.pre_order_traversal(node.right)
# 中序遍历 (左-根-右)
def in_order_traversal(self, node=None):
if node is None:
node = self.root
if node:
self.in_order_traversal(node.left)
print(node.value, end=" -> ")
self.in_order_traversal(node.right)
# 后序遍历 (左-右-根)
def post_order_traversal(self, node=None):
if node is None:
node = self.root
if node:
self.post_order_traversal(node.left)
self.post_order_traversal(node.right)
print(node.value, end=" -> ")
# 示例
tree = BinaryTree()
tree.insert(5)
tree.insert(3)
tree.insert(7)
tree.insert(2)
tree.insert(4)
tree.insert(6)
tree.insert(8)
# 遍历
print("前序遍历:")
tree.pre_order_traversal()
print("\n中序遍历:")
tree.in_order_traversal()
print("\n后序遍历:")
tree.post_order_traversal()
```
阅读全文