题目描述
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 :
输入:root = [3,9,20,null,null,15,7]
输出:2
思路分析
① 保存一个全局遍历 min 作为最小深度。
② 搜索叶子节点,将该节点的深度 level 与 min 比较,取较小者。
代码描述
使用 Java 进行代码描述:
class Solution {
int min = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
if (root == null) return 0;
minDepth(root, 1);
return min;
}
public void minDepth(TreeNode root, int level) {
if (root == null) return;
// 如果是叶子节点,保存最小值
if (root.left == null && root.right == null) min = Math.min(min, level);
// 继续找叶子节点
minDepth(root.left, level + 1);
minDepth(root.right, level + 1);
}
}
显然,上面的代码中,如果层级大于等于 min ,是没有必要继续递归的,因此增加了一行代码:
class Solution {
int min = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
if (root == null) return 0;
minDepth(root, 1);
return min;
}
public void minDepth(TreeNode root, int level) {
if (root == null) return;
if (root.left == null && root.right == null) min = Math.min(min, level);
// 增加了一行代码
if (level >= min) return;
minDepth(root.left, level + 1);
minDepth(root.right, level + 1);
}
}
技术公众号:小猿君的算法笔记
更多精彩,可以关注公众号【小猿君的算法笔记】,如有不足请在评论区指出。
如果本文对你有帮助,👍支持下呗。