解 队列
分析
- 用队列存放节点 先进先出
- 每次进入循环时 弹出该层所有节点
- 每次循环末尾 result添加该层节点val列表
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
result = list()
if not root:
return []
# 队列
q = list()
q.append(root)
while q:
# 存放该层节点的val
order = list()
# 该层节点个数
n = len(q)
for i in range(n):
# 出队列
node = q.pop(0)
# 记录该节点val
order.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
# 切片 浅拷贝
result.append(order[:])
return result