派大鑫的科研站 2021-12-16 18:57 采纳率: 61.5%
浏览 20
已结题

二叉树遍历出现了问题


def preoder(root):
    p1=[]
    if root:
        p1.append(root.data)
        p1+=preoder(root.left)
        p1+=preoder(root.right)
        return p1
L1=preoder(B1.rootNode)
print(L1)
Traceback (most recent call last):
  File "D:\The beauty of the algorithm\c3\Binary tree_traverse.py", line 54, in <module>
    L1=preoder(B1.rootNode)
  File "D:\The beauty of the algorithm\c3\Binary tree_traverse.py", line 51, in preoder
    p1+=preoder(root.left)
  File "D:\The beauty of the algorithm\c3\Binary tree_traverse.py", line 51, in preoder
    p1+=preoder(root.left)
  File "D:\The beauty of the algorithm\c3\Binary tree_traverse.py", line 51, in preoder
    p1+=preoder(root.left)
  [Previous line repeated 1 more time]
TypeError: 'NoneType' object is not iterable


  • 写回答

1条回答 默认 最新

  • 陈年椰子 2021-12-17 09:27
    关注

    从逻辑上看,

    p1+=preoder(root.left)
    p1+=preoder(root.right)
    
    

    这两句前,都要判断是否为None吧。

    if root.left:
        p1+=preoder(root.left)
    if root.right:
        p1+=preoder(root.right)
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    问题事件

    • 系统已结题 12月29日
    • 已采纳回答 12月21日
    • 创建了问题 12月16日

    悬赏问题

    • ¥15 如何通过求后验分布求得样本中属于两种物种其中一种的概率?
    • ¥15 q从常量变成sin函数,怎么改写python代码?
    • ¥15 图论编程问题,有可以指导的吗
    • ¥15 DEA的CCR模型画图
    • ¥15 请假各位一个关于安卓车机的问题
    • ¥15 光谱仪怎么看这样的透射谱
    • ¥15 pyqt5 如何实现输入框输入关键词,下拉框显示模糊查询返回的结果?
    • ¥20 fluent模拟,可以燃烧和相变同时模拟吗?
    • ¥50 海康摄像头,C#如何识别车牌号码和抓取JPG
    • ¥15 yolov5 pt转engine的问题