LeetCode 题解工作台

二叉树的层序遍历

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。 示例 1: 输入: root = [3,9,20,null,null,15,7] 输出: [[3],[9,20],[15,7]] 示例 2: 输入: root = [1] 输出: [[1]] 示例 3…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

我们可以使用 BFS 的方法来解决这道题。首先将根节点入队,然后不断地进行以下操作,直到队列为空: - 遍历当前队列中的所有节点,将它们的值存储到一个临时数组 中,然后将它们的孩子节点入队。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

 

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]

示例 2:

输入:root = [1]
输出:[[1]]

示例 3:

输入:root = []
输出:[]

 

提示:

  • 树中节点数目在范围 [0, 2000]
  • -1000 <= Node.val <= 1000
lightbulb

解题思路

方法一:BFS

我们可以使用 BFS 的方法来解决这道题。首先将根节点入队,然后不断地进行以下操作,直到队列为空:

  • 遍历当前队列中的所有节点,将它们的值存储到一个临时数组 tt 中,然后将它们的孩子节点入队。
  • 将临时数组 tt 存储到答案数组中。

最后返回答案数组即可。

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

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 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]]:
        ans = []
        if root is None:
            return ans
        q = deque([root])
        while q:
            t = []
            for _ in range(len(q)):
                node = q.popleft()
                t.append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            ans.append(t)
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you understand how to perform BFS traversal using a queue?

  • question_mark

    Can you explain why BFS is appropriate for this problem?

  • question_mark

    Are you able to handle edge cases like an empty tree or a tree with a single node?

warning

常见陷阱

外企场景
  • error

    Misunderstanding the level order traversal concept and treating it as a depth-first traversal.

  • error

    Failing to properly manage the queue to ensure that nodes are processed level by level.

  • error

    Not accounting for edge cases such as an empty tree or single-node tree, which require special handling.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Spiral Level Order Traversal

  • arrow_right_alt

    Zigzag Level Order Traversal

  • arrow_right_alt

    Reverse Level Order Traversal

help

常见问题

外企场景

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