LeetCode 题解工作台

二叉树的最小深度

给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明: 叶子节点是指没有子节点的节点。 示例 1: 输入: root = [3,9,20,null,null,15,7] 输出: 2 示例 2: 输入: root = [2,null,3,null,4,nul…

category

4

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 二分·树·traversal

bolt

答案摘要

递归的终止条件是当前节点为空,此时返回 ;如果当前节点左右子树有一个为空,返回不为空的子树的最小深度加 ;如果当前节点左右子树都不为空,返回左右子树最小深度的较小值加 。 时间复杂度 ,空间复杂度 。其中 是二叉树的节点个数。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。

 

示例 1:

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

示例 2:

输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

 

提示:

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

解题思路

方法一:递归

递归的终止条件是当前节点为空,此时返回 00;如果当前节点左右子树有一个为空,返回不为空的子树的最小深度加 11;如果当前节点左右子树都不为空,返回左右子树最小深度的较小值加 11

时间复杂度 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
# 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 minDepth(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        if root.left is None:
            return 1 + self.minDepth(root.right)
        if root.right is None:
            return 1 + self.minDepth(root.left)
        return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Do you understand the difference between BFS and DFS for this problem?

  • question_mark

    Can you explain how early exit can improve the DFS approach?

  • question_mark

    Will you consider edge cases such as an empty tree or trees with only one branch?

warning

常见陷阱

外企场景
  • error

    Not considering edge cases like empty trees or a single-node tree.

  • error

    Forgetting to handle unbalanced trees where one side is deeper than the other.

  • error

    Misunderstanding the depth of the tree, confusing the total number of nodes with the path to a leaf node.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find the maximum depth of a binary tree using the same traversal methods.

  • arrow_right_alt

    Solve for the depth of a binary tree where each node has only one child.

  • arrow_right_alt

    Determine the depth of a binary search tree and compare it with its balanced version.

help

常见问题

外企场景

二叉树的最小深度题解:二分·树·traversal | LeetCode #111 简单