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

二叉树遍历出现了问题


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日