建立一棵二叉树,编程实现二叉树的如下基本操作: 1. 按先序序列构造一棵二叉链表表示的二叉树T; 2. 对这棵二叉树进行遍历:先序、中序、后序以及层次遍历,分别输出结点的遍历序列; 3. 求二叉树的深度/结点数目/叶结点数目; 4. 将二叉树每个结点的左右子树交换位置。(选做)
时间: 2024-12-17 13:13:06 浏览: 1
头歌数据结构二叉树的二叉链表存储及基本操作
5星 · 资源好评率100%
建立一棵二叉树并进行基本操作的编程实现通常涉及到数据结构的理解和递归算法的运用。以下是Python中一种常见的做法:
```python
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_binary_tree(preorder):
if not preorder:
return None
root_val = preorder[0]
root = Node(root_val)
index = 1
i = 1
while i < len(preorder):
if preorder[i] < root_val:
root.left = build_binary_tree(preorder[index:i])
index = i + 1
else:
root.right = build_binary_tree(preorder[index:])
break
i += 1
return root
# 先序遍历
def pre_order_traversal(node):
if node is not None:
print(node.val, end=" ")
pre_order_traversal(node.left)
pre_order_traversal(node.right)
# 中序遍历
def in_order_traversal(node):
if node is not None:
in_order_traversal(node.left)
print(node.val, end=" ")
in_order_traversal(node.right)
# 后序遍历
def post_order_traversal(node):
if node is not None:
post_order_traversal(node.left)
post_order_traversal(node.right)
print(node.val, end=" ")
# 层次遍历 (广度优先搜索)
from collections import deque
def level_order_traversal(node):
if node is None:
return []
queue = deque([node])
traversal = []
while queue:
level_size = len(queue)
current_level = [queue.popleft().val for _ in range(level_size)]
traversal.extend(current_level)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return traversal
# 计算深度
def depth(node):
if node is None:
return 0
return max(depth(node.left), depth(node.right)) + 1
# 统计节点数和叶节点数
def count_nodes(node):
if node is None:
return 0, 0
left_count, left_leaf_count = count_nodes(node.left)
right_count, right_leaf_count = count_nodes(node.right)
total_count = left_count + right_count + 1
leaf_count = left_leaf_count + right_leaf_count + (1 if node.left is None and node.right is None else 0)
return total_count, leaf_count
# 子节点交换
def swap_subtrees(node):
if node.left and node.right:
node.left, node.right = node.right, node.left
swap_subtrees(node.left)
swap_subtrees(node.right)
# 示例使用
preorder = [5, 3, 7, 2, 4, 6, 8]
root = build_binary_tree(preorder)
print("Preorder:", pre_order_traversal(root))
print("Inorder:", in_order_traversal(root))
print("Postorder:", post_order_traversal(root))
print("Level Order:", level_order_traversal(root))
depth_of_tree = depth(root)
total_nodes, leaf_nodes = count_nodes(root)
print(f"Depth: {depth_of_tree}, Nodes: {total_nodes}, Leaf Nodes: {leaf_nodes}")
swap_subtrees(root)
```
以上代码实现了按照给定的先序遍历序列构建二叉树,并对树进行了各种遍历以及计算相关属性。对于第四个选项“将二叉树每个结点的左右子树交换位置”,我们已经提供了一个简单的函数`swap_subtrees`来完成这个操作。
阅读全文