leetcode 102. 二叉树的层次遍历

题目链接:leetcode

思路:广度优先遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:return []
q = deque()
q.append(root)
res = []
while q:
tmp = []
n = len(q)
for i in range(n):
node = q.popleft()
tmp.append(node.val)
if node.left:q.append(node.left)
if node.right:q.append(node.right)
res.append(tmp)
return res