python代码:使用递归算法对一颗满二叉树(如下示例)完成以下任务。 4 2 7 1 3 6 9 1)输出该二叉树; 2)对该二叉树进行前序、中序、后序遍历; 3)翻转这棵二叉树。
时间: 2024-09-23 11:04:57 浏览: 45
python实现二叉树的遍历
在Python中,我们可以使用递归的方式来处理满二叉树。首先,我们需要定义一个节点类,然后创建一个函数来构建满二叉树,并实现递归遍历(前序、中序、后序)以及翻转操作。
```python
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def build_full_binary_tree(n):
if n <= 0:
return None
mid = n // 2
root = Node(n)
root.left = build_full_binary_tree(mid - 1)
root.right = build_full_binary_tree(n - mid)
return root
# 输出二叉树
def print_tree(node, level=0):
if node is not None:
print(' ' * level + str(node.value))
print_tree(node.left, level+1)
print_tree(node.right, level+1)
# 遍历二叉树
def traverse_tree(node, order='preorder'):
if node is None:
return
if order == 'preorder':
print(node.value, end=' ')
traverse_tree(node.left)
traverse_tree(node.right)
elif order == 'inorder':
traverse_tree(node.left)
print(node.value, end=' ')
traverse_tree(node.right)
elif order == 'postorder':
traverse_tree(node.left)
traverse_tree(node.right)
print(node.value, end=' ')
# 翻转二叉树
def invert_tree(node):
if node is None:
return None
node.left, node.right = node.right, node.left
invert_tree(node.left)
invert_tree(node.right)
# 示例
root = build_full_binary_tree(4)
print("Original Tree:")
print_tree(root)
traverse_tree(root, 'preorder') # 前序遍历
traverse_tree(root, 'inorder') # 中序遍历
traverse_tree(root, 'postorder') # 后序遍历
invert_tree(root) # 翻转树
print("\nInverted Tree:")
print_tree(root)
```
阅读全文