编写一程序构造二叉树b,并输出二叉树b的叶子结点个数以及叶子结点对应的字符
时间: 2024-12-13 13:27:11 浏览: 8
首先,我们需要定义一个二叉树节点结构,包括数据和指向左右子节点的指针。然后我们可以创建一个函数来构建二叉树,并遍历这个树来找出所有叶子节点及其对应的字符。
```python
# 定义二叉树节点
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def build_binary_tree(b, root_data):
# 根据给定的数据列表构建二叉树
if b:
mid = len(b) // 2
root = TreeNode(b[mid])
root.left = build_binary_tree(b[:mid], "") if mid > 0 else None
root.right = build_binary_tree(b[mid + 1:], "") if mid < len(b) - 1 else None
return root
def count_leaf_nodes_and_chars(root):
leaf_count = 0
leaf_nodes = []
def is_leaf(node):
return node.left is None and node.right is None
def traverse(node, char=None):
nonlocal leaf_count
if node is not None:
char = node.data if is_leaf(node) else char
if is_leaf(node):
leaf_count += 1
leaf_nodes.append(char)
traverse(node.left, char)
traverse(node.right, char)
traverse(root)
return leaf_count, leaf_nodes
# 示例:输入一个字符串列表构建二叉树
b = ["A", "B", "D", "E", "F", "G"]
root = build_binary_tree(b, "")
# 计算并输出结果
leaf_count, leaf_chars = count_leaf_nodes_and_chars(root)
print(f"叶子节点个数: {leaf_count}")
print(f"叶子节点对应的字符: {leaf_chars}")
阅读全文