【LC】111. 二叉树的最小深度

题目描述:

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

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

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

示例 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.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        return dfs(root);
    }
 
    private int dfs(TreeNode node) {
        if (node == null) {
            return 0;
        }
        if (node.left == null && node.right == null) {
            return 1;
        }
        int minDepth = Integer.MAX_VALUE;
        if (node.left != null) {
            minDepth = Math.min(dfs(node.left), minDepth);
            
        }
        if (node.right != null) {
            minDepth = Math.min(dfs(node.right), minDepth);
        }
        return minDepth + 1;
    }
}
相关推荐
孟陬20 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端
想用offer打牌20 小时前
一站式了解四种限流算法
java·后端·go
华仔啊20 小时前
Java 开发千万别给布尔变量加 is 前缀!很容易背锅
java
也些宝21 小时前
Java单例模式:饿汉、懒汉、DCL三种实现及最佳实践
java
Gorway21 小时前
解析残差网络 (ResNet)
算法
拖拉斯旋风21 小时前
LeetCode 经典算法题解析:优先队列与广度优先搜索的巧妙应用
算法
Wect21 小时前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript
Nyarlathotep01131 天前
SpringBoot Starter的用法以及原理
java·spring boot
wuwen51 天前
WebFlux + Lettuce Reactive 中 SkyWalking 链路上下文丢失的修复实践
java