基于Python字典构建二叉树:树形打印异常问题求助
二叉树打印异常排查与修复
问题原因
- 节点创建逻辑错误:原代码中,若节点不在
data字典里(比如Akon、Frank这类无下属的员工),直接返回None,导致这些节点根本没被实例化为TreeNode对象。实际上这类节点是叶子节点,应当被创建,只是没有子节点。 - 空值处理逻辑无问题,但被节点创建错误掩盖:原代码对子节点为
None的情况已有判断,但核心问题是叶子节点未被创建,导致打印时缺失层级。
修复方案
修改construct_binary_tree函数:
- 优先创建当前节点,无论它是否在
data中(不在则为叶子节点) - 仅当节点存在于
data中时,才处理其下属子节点 - 子节点为
None时跳过创建
修复后的完整代码
class TreeNode: def __init__(self, key): self.key = key self.left = None self.right = None def construct_binary_tree(data, root_key): # 空值直接返回None,不创建节点 if root_key is None: return None # 先创建当前节点,无论是否有下属 print("Constructing node:", root_key) root = TreeNode(root_key) # 仅当节点在data中时,处理子节点 if root_key in data: children = data[root_key] left_child_key = children[0] if len(children) > 0 else None right_child_key = children[1] if len(children) > 1 else None print("Left child of", root_key, ":", left_child_key) print("Right child of", root_key, ":", right_child_key) root.left = construct_binary_tree(data, left_child_key) root.right = construct_binary_tree(data, right_child_key) return root def print_tree(root, depth=0): if root: print(" " * depth + f"|-- {root.key}") print_tree(root.left, depth + 1) print_tree(root.right, depth + 1) # 完整的经理-员工数据 data = { "Amy": ["Alice", "Charlie"], "Alice": ["Akon", "Eve"], "Eve": ["Frank", None], "Charlie": ["Bob", "Grace"] } # 构建二叉树 root_key = next(iter(data)) root = construct_binary_tree(data, root_key) # 打印树形结构 print("\n树形结构输出:") print_tree(root)
运行结果
Constructing node: Amy Left child of Amy : Alice Right child of Amy : Charlie Constructing node: Alice Left child of Alice : Akon Right child of Alice : Eve Constructing node: Akon Constructing node: Eve Left child of Eve : Frank Right child of Eve : None Constructing node: Frank Constructing node: Charlie Left child of Charlie : Bob Right child of Charlie : Grace Constructing node: Bob Constructing node: Grace 树形结构输出: |-- Amy |-- Alice |-- Akon |-- Eve |-- Frank |-- Charlie |-- Bob |-- Grace
内容的提问来源于stack exchange,提问作者user2657189
相关产品推荐
相关产品推荐

