二叉树遍历出现了问题


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


从逻辑上看,

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

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

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