【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 分钟前
JDBC从入门到面试:全面掌握Java数据库连接技术
java·数据库·面试
潇I洒1 小时前
若依4.8.1打包war后在Tomcat无法运行,404报错的一个解决方法
java·tomcat·ruoyi·若依·404
kyle~1 小时前
排序---插入排序(Insertion Sort)
c语言·数据结构·c++·算法·排序算法
Funcy1 小时前
XxlJob 源码分析05:执行器注册流程
java
Boop_wu1 小时前
[数据结构] 队列 (Queue)
java·jvm·算法
无敌的神原秋人1 小时前
关于Redis不同序列化压缩性能的对比
java·redis·缓存
hn小菜鸡2 小时前
LeetCode 3643.垂直翻转子矩阵
算法·leetcode·矩阵
2301_770373732 小时前
数据结构之跳表
数据结构
散1122 小时前
01数据结构-初探动态规划
数据结构·动态规划