python写一个二叉树
时间: 2023-04-09 21:03:18 浏览: 103
可以的,以下是一个简单的 Python 二叉树实现:
```python
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, value):
if self.root is None:
self.root = Node(value)
else:
self._insert(value, self.root)
def _insert(self, value, current_node):
if value < current_node.value:
if current_node.left is None:
current_node.left = Node(value)
else:
self._insert(value, current_node.left)
elif value > current_node.value:
if current_node.right is None:
current_node.right = Node(value)
else:
self._insert(value, current_node.right)
else:
print("Value already in tree!")
def print_tree(self):
if self.root is not None:
self._print_tree(self.root)
def _print_tree(self, current_node):
if current_node is not None:
self._print_tree(current_node.left)
print(str(current_node.value))
self._print_tree(current_node.right)
# Example usage:
tree = BinaryTree()
tree.insert(5)
tree.insert(3)
tree.insert(7)
tree.insert(1)
tree.insert(9)
tree.print_tree()
```
这个二叉树实现包括节点插入和打印树的功能。你可以根据需要进行修改和扩展。
阅读全文