← [ BACK_TO_NOTES ]

Minimum Depth of Binary Tree

LeetCode 111 二叉树最小深度:BFS 见到第一个叶子即返回;DFS 注意空子树处理。

#algorithm #snippet #evergreen #tree #bfs #dfs #leetcode

[!info] related notes 算法面试题型 MOC 二叉树高频题

Minimum Depth of Binary Tree

LeetCode: https://leetcode.cn/problems/minimum-depth-of-binary-tree/

推荐:BFS

深度按根到叶子的路径节点数计。叶子必须左右孩子都为空,缺少某一个孩子不算叶子。BFS 第一次遇到叶子时的层数就是答案;例如根只有一个叶子孩子时,最小深度为 2 而非 1。

import java.util.*;

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int depth = 1;
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = q.poll();
                if (cur.left == null && cur.right == null) return depth;
                if (cur.left != null) q.add(cur.left);
                if (cur.right != null) q.add(cur.right);
            }
            depth++;
        }
        return depth;
    }
}

DFS 注意点

  • 如果一个子树为空,最小深度不能取 min(left,right) 直接得到 0,需要特殊处理。

Java 示例使用题目提供的 TreeNode。最坏时间 O(n),队列 O(w);BFS 可在首个叶子处提前停止,不保证只访问最短路径上的节点。

创建于 2026/3/16 更新于 2026/10/7
Digital Biome
Access

键盘导航

j / k / ↑ / ↓
选择对象
Enter / o
打开选择
/ 或 Ctrl+K
全站搜索
i / f / 1–4
筛选当前列表
g → h / l / p / t / a
首页 / 笔记 / 项目 / 工具 / About
r → 1–9
打开所选对象的关联
u
返回上一页
Esc
关闭浮层 / 取消命令;输入框内清空文本