LeetCode 题解工作台

找树左下角的值

给定一个二叉树的 根节点 root ,请找出该二叉树的 最底层 最左边 节点的值。 假设二叉树中至少有一个节点。 示例 1: 输入: root = [2,1,3] 输出: 1 示例 2: 输入: [1,2,3,4,null,5,6,null,null,7] 输出: 7 提示: 二叉树的节点个数的范围…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

BFS 找最后一层第一个节点。 class Solution:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。

假设二叉树中至少有一个节点。

 

示例 1:

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

示例 2:

输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7

 

提示:

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

解题思路

方法一:BFS

BFS 找最后一层第一个节点。

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

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Tests the candidate's understanding of binary tree traversal techniques.

  • question_mark

    Evaluates their ability to track state across recursive or iterative calls.

  • question_mark

    Assesses how well they handle edge cases like trees with only one node or very unbalanced trees.

warning

常见陷阱

外企场景
  • error

    Forgetting to track the leftmost value at the deepest level, leading to an incorrect answer.

  • error

    Failing to handle edge cases such as when the tree only contains one node or is unbalanced.

  • error

    Using an inefficient traversal strategy that doesn't take advantage of level-order exploration.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider the scenario where you need to find the rightmost value of the last row instead of the leftmost.

  • arrow_right_alt

    What if the tree is a sparse binary tree with large depth?

  • arrow_right_alt

    How would the solution change if the task was to return the bottom-most value for any given row, not just the last row?

help

常见问题

外企场景

找树左下角的值题解:二分·树·traversal | LeetCode #513 中等