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]]:
res = []
# 空节点,直接返回
if not root:
return res
que = [root]
while que:
# 暂存下一层节点的队列
next_ceng = []
# 暂存当前节点的值队列
temp = []
for node in que:
temp.append(node.val)
# 获取当前节点的 左右子节点
left = node.left
right = node.right
if left:
next_ceng.append(left)
if right:
next_ceng.append(right)
# 把当前层节点对应的值加到结果中
res.append(temp)
# 当前层队列中节点遍历完成,开始处理下层节点
que = next_ceng
return res
Pyhton 二叉树层级遍历
最新推荐文章于 2024-08-23 14:54:20 发布