You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 09:09:11