LeetCode 题解工作台

在每个树行中找最大值

给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。 示例1: 输入: root = [1,3,2,5,3,null,9] 输出: [1,3,9] 示例2: 输入: root = [1,2,3] 输出: [1,3] 提示: 二叉树的节点个数的范围是 [0,10 4 ] -2 31 3…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

我们定义一个队列 ,将根节点放入队列中。每次从队列中取出当前层的所有节点,找出最大值,然后将下一层的所有节点放入队列中,直到队列为空。 时间复杂度 ,空间复杂度 。其中 是二叉树的节点个数。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。

 

示例1:

输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]

示例2:

输入: root = [1,2,3]
输出: [1,3]

 

提示:

  • 二叉树的节点个数的范围是 [0,104]
  • -231 <= Node.val <= 231 - 1

 

lightbulb

解题思路

方法一:BFS

我们定义一个队列 qq,将根节点放入队列中。每次从队列中取出当前层的所有节点,找出最大值,然后将下一层的所有节点放入队列中,直到队列为空。

时间复杂度 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 largestValues(self, root: Optional[TreeNode]) -> List[int]:
        ans = []
        if root is None:
            return ans
        q = deque([root])
        while q:
            x = -inf
            for _ in range(len(q)):
                node = q.popleft()
                x = max(x, node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            ans.append(x)
        return ans
speed

复杂度分析

指标
时间O(n)
空间O(h)
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate demonstrates familiarity with tree traversal techniques like DFS and BFS.

  • question_mark

    The candidate tracks row-wise maximum values accurately.

  • question_mark

    The candidate optimizes space usage during the tree traversal.

warning

常见陷阱

外企场景
  • error

    Not handling edge cases, like empty trees or trees with only one node.

  • error

    Confusing the traversal order, leading to incorrect row-wise maximums.

  • error

    Failing to update the maximum value correctly across all rows.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Finding the second largest value in each row.

  • arrow_right_alt

    Handling trees that contain non-unique values within a row.

  • arrow_right_alt

    Optimizing for memory usage in sparse trees.

help

常见问题

外企场景

在每个树行中找最大值题解:二分·树·traversal | LeetCode #515 中等