LeetCode 题解工作台

层数最深叶子节点的和

给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和 。 示例 1: 输入: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] 输出: 15 示例 2: 输入: root = [6,7,8,2,7,1,3,9,null,1,4,nul…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

我们可以使用广度优先搜索,逐层遍历二叉树,并在遍历到每一层时计算该层的节点值之和。遍历完成后,返回最后一层的节点值之和。 时间复杂度 ,空间复杂度 。其中 是树中节点的数目。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和

 

示例 1:

输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15

示例 2:

输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
输出:19

 

提示:

  • 树中节点数目在范围 [1, 104] 之间。
  • 1 <= Node.val <= 100
lightbulb

解题思路

方法一:BFS

我们可以使用广度优先搜索,逐层遍历二叉树,并在遍历到每一层时计算该层的节点值之和。遍历完成后,返回最后一层的节点值之和。

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

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Tests the candidate's understanding of tree traversal techniques.

  • question_mark

    Evaluates problem-solving strategies related to tree depth and leaf-level summing.

  • question_mark

    Looks for the candidate's ability to choose between BFS and DFS based on problem needs.

warning

常见陷阱

外企场景
  • error

    Misunderstanding the problem’s requirement to only sum the deepest leaves.

  • error

    Confusing the depth of the tree with the level of leaves.

  • error

    Incorrectly handling the case when there is only one node in the tree.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Change the tree structure to allow non-binary trees and ask for the sum of deepest leaves.

  • arrow_right_alt

    Ask for the sum of the deepest odd or even numbered leaves.

  • arrow_right_alt

    Add extra constraints like calculating the sum at multiple levels, not just the deepest.

help

常见问题

外企场景

层数最深叶子节点的和题解:二分·树·traversal | LeetCode #1302 中等