请将上述代码整合成一个完整的代码
时间: 2024-05-03 12:22:42 浏览: 229
以下是整合后的完整代码:
```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):
new_node = Node(value)
if self.root is None:
self.root = new_node
else:
current_node = self.root
while True:
if value < current_node.value:
if current_node.left is None:
current_node.left = new_node
break
else:
current_node = current_node.left
elif value > current_node.value:
if current_node.right is None:
current_node.right = new_node
break
else:
current_node = current_node.right
def inorder_traversal(self, node):
if node is not None:
self.inorder_traversal(node.left)
print(node.value)
self.inorder_traversal(node.right)
def preorder_traversal(self, node):
if node is not None:
print(node.value)
self.preorder_traversal(node.left)
self.preorder_traversal(node.right)
def postorder_traversal(self, node):
if node is not None:
self.postorder_traversal(node.left)
self.postorder_traversal(node.right)
print(node.value)
# Test
tree = BinaryTree()
tree.insert(4)
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(6)
tree.insert(5)
tree.insert(7)
print("Inorder traversal:")
tree.inorder_traversal(tree.root)
print("Preorder traversal:")
tree.preorder_traversal(tree.root)
print("Postorder traversal:")
tree.postorder_traversal(tree.root)
```
阅读全文