LeetCode 题解工作台
二叉树的最小深度
给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明: 叶子节点是指没有子节点的节点。 示例 1: 输入: root = [3,9,20,null,null,15,7] 输出: 2 示例 2: 输入: root = [2,null,3,null,4,nul…
4
题型
8
代码语言
3
相关题
当前训练重点
简单 · 二分·树·traversal
答案摘要
递归的终止条件是当前节点为空,此时返回 ;如果当前节点左右子树有一个为空,返回不为空的子树的最小深度加 ;如果当前节点左右子树都不为空,返回左右子树最小深度的较小值加 。 时间复杂度 ,空间复杂度 。其中 是二叉树的节点个数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 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
解题思路
方法一:递归
递归的终止条件是当前节点为空,此时返回 ;如果当前节点左右子树有一个为空,返回不为空的子树的最小深度加 ;如果当前节点左右子树都不为空,返回左右子树最小深度的较小值加 。
时间复杂度 ,空间复杂度 。其中 是二叉树的节点个数。
# 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))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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?
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.