class Solution:
def levelOrder(self , root: TreeNode) -> List[List[int]]:
# write code here
current_layer_nodes = [root] if root else []
ret = []
# 当当前层不为空列表的时候,说明还没有到底层
while current_layer_nodes:
curr_result = []
next_layer_nodes = []
# 遍历本层的所有节点(来自于上一层的存储)
for n in current_layer_nodes:
curr_result.append(n.val)
# 存储下一层的节点
if n.left:
next_layer_nodes.append(n.left)
if n.right:
next_layer_nodes.append(n.right)
# 将当前层的结果存入返回的列表中
ret.append(curr_result)
# 重置当前层为下一层,往下走。
current_layer_nodes = next_layer_nodes
return ret