1 """ 2 Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 For example: 4 Given binary tree [3,9,20,null,null,15,7], 5 3 6 / 7 9 20 8 / 9 15 7 10 return its level order traversal as: 11 [ 12 [3], 13 [9,20], 14 [15,7] 15 ] 16 17 """ 18 class TreeNode: 19 def __init__(self, x): 20 self.val = x 21 self.left = None 22 self.right = None 23 24 class Solution: 25 def levelOrder(self, root): 26 if root == None: #树为空,直接返回[] 27 return [] 28 queue = [root] 29 cur = [] 30 res = [] 31 while queue: 32 cur = [x.val if x else None for x in queue] #存当前层的value 33 newqueue = [] #newqueue用来遍历下一层使用 34 for x in queue: 35 if x.left: #bug 如果不判断,结果包含[None] 36 newqueue.append(x.left) 37 if x.right: 38 newqueue.append(x.right) 39 queue = newqueue 40 res.append(cur) #将当前[]append到最后结果 41 return res 42 """ 43 本题与leetcode101相似,用BFS可解 44 """