思路: 一开始没想好怎么控制打印每层多少个,后来发现可以依据队列长度进行控制。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None: # 空树
return []
result = []
que = collections.deque()
que.append(root)
while que:
tmp_lst = []
for i in range(len(que)):
poped = que.popleft()
tmp_lst.append(poped.val)
if poped.left:
que.append(poped.left)
if poped.right:
que.append(poped.right)
result.append(tmp_lst)
return result