1.代码
from collections import deque
from typing import List
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
i = 0
queue = deque()
result : List[List[int]] = []
if root==None:
return result
queue.append(root)
while(queue):
length = len(queue)
result.append([])
for j in range (length):
item = queue.popleft()
if item.left:
queue.append(item.left)
if item.right:
queue.append(item.right)
result[i].append(item.val)
i=i+1
return result
2.思路
用一个队列控制遍历,一开始队列中只有root,每一次通过检查队列的长度,控制出队的元素个数恰好为一层的个数。每次一个元素出队,依次将它的左右子节点入队,并计入result中对应数组。