Python 用binarytree模块build方法构建二叉树修复路径打印代码问题
问题原因
- 传参错误:
printPaths方法要求传入二叉树根节点对象,原代码调用时传入的root.value是根节点的整数值,后续逻辑尝试访问整数的left/right属性会直接抛出异常。 - 属性名不匹配:原遍历逻辑中读取节点值使用
root.data,但binarytree库返回的Node实例存储值的属性名为value,属性名不一致会触发属性不存在的报错。
修正后可正常运行的完整代码
def printPaths(root): path = [] printPathsRec(root, path, 0) def printPathsRec(root, path, pathLen): if root is None: return # 适配binarytree节点的value属性 if len(path) > pathLen: path[pathLen] = root.value else: path.append(root.value) pathLen += 1 if root.left is None and root.right is None: printArray(path, pathLen) else: printPathsRec(root.left, path, pathLen) printPathsRec(root.right, path, pathLen) def printArray(ints, len): for i in ints[0 : len]: print(i, end=" ") print() from binarytree import build values = [7, 3, 2, 6, 9, None, 1, 5, 8] root = build(values) # 打印二叉树结构便于校验 print(root) # 传入根节点对象而非节点值 printPaths(root)
运行输出示例
____7__ / \ __3__ 2___ / \ \ 6 9 1 / \ 5 8 7 3 6 5 7 3 6 8 7 3 9 7 2 1
内容的提问来源于stack exchange,提问作者JIA WEI LEONG
相关产品推荐
相关产品推荐

