编写算法,建立一棵由n个结点构成的二叉树的二叉链表存储结构(n由学生自己确定),以空格代表结点的某指针域为空。并对其进行先序、中序遍历,并计算二叉树的深度、二叉树的叶子结点的个数。然后用先序序列和中序序列重新构造一棵二叉树,并验证构造结果的正确性。
时间: 2024-12-19 21:20:52 浏览: 3
数据结构实验报告-树-二叉树的字符图形显示程序(半期测试)-实验内容与要求.docx
5星 · 资源好评率100%
首先,为了编写这样的算法,我们需要创建一个二叉树节点类,包含数据值、左孩子和右孩子的引用。在二叉链表存储结构中,我们会用null表示空指针。
```python
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def build_binary_tree(n, values): # 先序和后序遍历构建二叉树
if n == 0:
return None
root = Node(values[0])
queue = [root]
i = 1
while i < n:
node = queue.pop(0)
if i+1 < n and values[i*2] is not None: # 先序遍历
node.left = Node(values[i*2])
queue.append(node.left)
if i+2 < n and values[i*2 + 1] is not None: # 后续遍历
node.right = Node(values[i*2 + 1])
queue.append(node.right)
i += 1
return root
def pre_order_traversal(node):
if node is not None:
print(node.value, 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.value, end=" ")
in_order_traversal(node.right)
# 计算深度
def max_depth(node):
if node is None:
return 0
else:
left_height = max_depth(node.left)
right_height = max_depth(node.right)
return max(left_height, right_height) + 1
# 计算叶节点数
def count_leaves(node):
if node is None:
return 0
elif node.left is None and node.right is None:
return 1
else:
return count_leaves(node.left) + count_leaves(node.right)
# 重建二叉树
def reconstruct_tree(preorder, inorder):
if len(preorder) == 0 or len(inorder) == 0:
return None
root_val = preorder[0]
root = Node(root_val)
in_index = inorder.index(root_val)
left_inorder = inorder[:in_index]
right_inorder = inorder[in_index + 1:]
root.left = reconstruct_tree(preorder[1:in_index+1], left_inorder)
root.right = reconstruct_tree(preorder[in_index+1:], right_inorder)
return root
# 验证重建结果
def verify_reconstruction(original_tree, reconstructed_tree):
if original_tree is None and reconstructed_tree is None:
return True
if original_tree.value != reconstructed_tree.value:
return False
return verify_reconstruction(original_tree.left, reconstructed_tree.left) and \
verify_reconstruction(original_tree.right, reconstructed_tree.right)
# 示例用法
n = 5
values = ... # 用户提供的n个数值
tree = build_binary_tree(n, values)
pre_order_traversal(tree)
print("\nDepth:", max_depth(tree))
print("Leaf nodes:", count_leaves(tree))
reconstructed_tree = reconstruct_tree(tree.pre_order(), tree.in_order())
print("\nReconstructed Tree:")
pre_order_traversal(reconstructed_tree)
print("\nVerifying reconstruction:", verify_reconstruction(tree, reconstructed_tree))
```
阅读全文