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

二叉树遍历出现了问题


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 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services