.编写程序实现二叉树的建树、先序递归遍历、中序递归遍历、后序递归遍历4个基本操作;(必须完成)
时间: 2024-01-27 21:03:53 浏览: 69
好的,以下是二叉树的建树、先序递归遍历、中序递归遍历、后序递归遍历这四个基本操作的程序实现:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BinaryTree:
def __init__(self):
self.root = None
def build_tree(self, nodes):
queue = [None] * len(nodes)
for i in range(len(nodes)):
if nodes[i] is not None:
node = TreeNode(nodes[i])
if i == 0:
self.root = node
else:
parent_index = (i - 1) // 2
if i % 2:
queue[parent_index].left = node
else:
queue[parent_index].right = node
queue[i] = node
def preorder_traversal(self, node):
if node is None:
return
print(node.val)
self.preorder_traversal(node.left)
self.preorder_traversal(node.right)
def inorder_traversal(self, node):
if node is None:
return
self.inorder_traversal(node.left)
print(node.val)
self.inorder_traversal(node.right)
def postorder_traversal(self, node):
if node is None:
return
self.postorder_traversal(node.left)
self.postorder_traversal(node.right)
print(node.val)
```
例如,如果我们要创建如下的二叉树:
```
1
/ \
2 3
/ \
4 5
```
可以这样调用上述程序:
```python
tree = BinaryTree()
tree.build_tree([1, 2, 3, 4, 5])
tree.preorder_traversal(tree.root)
tree.inorder_traversal(tree.root)
tree.postorder_traversal(tree.root)
```
输出结果如下:
```
1
2
4
5
3
4
2
5
1
```
阅读全文