https://leetcode.com/problems/binary-tree-level-order-traversal/description/
二叉树层序遍历
思路:经典的队列问题
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import queue
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
res = []
q = queue.Queue()
q.put(root)
while q.qsize() > 0: #队列非空时,每次遍历一层
n = q.qsize() #该层大小
data = [] #该层数据
for i in range(n): #遍历该层
node = q.get() #从队列中取出结点
data.append(node.val) #记录数据
#左右子入队
if node.left:
q.put(node.left)
if node.right:
q.put(node.right)
res.append(data)
return res