LeetCode 题解工作台
N 叉树的层序遍历
给定一个 N 叉树,返回其节点值的 层序遍历 。(即从左到右,逐层遍历)。 树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。 示例 1: 输入: root = [1,null,3,2,4,null,5,6] 输出: [[1],[3,2,4],[5,6]] 示例 2: 输入:…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
我们首先判断根节点是否为空,若为空则直接返回空列表。 否则,我们创建一个队列 ,初始时将根节点加入队列。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。
树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。
示例 1:

输入:root = [1,null,3,2,4,null,5,6] 输出:[[1],[3,2,4],[5,6]]
示例 2:

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] 输出:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
提示:
- 树的高度不会超过
1000 - 树的节点总数在
[0, 104]之间
解题思路
方法一:BFS
我们首先判断根节点是否为空,若为空则直接返回空列表。
否则,我们创建一个队列 ,初始时将根节点加入队列。
当队列不为空时,我们循环以下操作:
- 创建一个空列表 ,用于存放当前层的节点值。
- 对于队列中的每个节点,将其值加入 中,并将其子节点加入队列。
- 将 加入结果列表 。
最后返回结果列表 。
时间复杂度 ,空间复杂度 。其中 为 N 叉树的节点数。
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
ans = []
if root is None:
return ans
q = deque([root])
while q:
t = []
for _ in range(len(q)):
root = q.popleft()
t.append(root.val)
q.extend(root.children)
ans.append(t)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N) because each node is visited once. Space complexity is O(W) where W is the maximum width of the tree, determined by the largest level, due to queue storage. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect discussion of BFS and level tracking.
- question_mark
Interviewer may ask about queue versus recursive approaches.
- question_mark
Clarify how you handle multiple children and null separators.
常见陷阱
外企场景- error
Merging nodes from different levels due to incorrect queue sizing.
- error
Ignoring null markers in the serialized input, causing misaligned levels.
- error
Failing to initialize lists for each level before adding node values.
进阶变体
外企场景- arrow_right_alt
Recursive DFS approach using depth parameter to append to level lists.
- arrow_right_alt
Reverse level order traversal for bottom-up grouping.
- arrow_right_alt
Level order traversal with alternating left-right or zigzag patterns.