LeetCode 题解工作台

N 叉树的层序遍历

给定一个 N 叉树,返回其节点值的 层序遍历 。(即从左到右,逐层遍历)。 树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。 示例 1: 输入: root = [1,null,3,2,4,null,5,6] 输出: [[1],[3,2,4],[5,6]] 示例 2: 输入:…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

我们首先判断根节点是否为空,若为空则直接返回空列表。 否则,我们创建一个队列 ,初始时将根节点加入队列。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个 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] 之间
lightbulb

解题思路

方法一:BFS

我们首先判断根节点是否为空,若为空则直接返回空列表。

否则,我们创建一个队列 qq,初始时将根节点加入队列。

当队列不为空时,我们循环以下操作:

  1. 创建一个空列表 tt,用于存放当前层的节点值。
  2. 对于队列中的每个节点,将其值加入 tt 中,并将其子节点加入队列。
  3. tt 加入结果列表 ansans

最后返回结果列表 ansans

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为 N 叉树的节点数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""
# 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
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

N 叉树的层序遍历题解:二分·树·traversal | LeetCode #429 中等