大家好🙌我是你们的好朋友,大数据老虾😀。相遇是缘,既然来了就拎着小板凳坐下来一起唠会儿😎,如果在文中有所收获,请别忘了一键三连,动动你发财的小手👍,你的鼓励,是我创作的动力😁!废话不多说,直接😎 开干吧!
PS:文末干货,记得拎着小板凳离开的时候也给它顺走 🤣
座右铭:“懒”对一个人的毁灭性有多大,早起的重要性就多大。
树-二叉树的最小深度
二叉树的最小深度
题目
给出一个二叉树,找出最小深度。
PS:最小深度是指从根节点到最近叶子节点的最短路径上的节点数量,叶子节点是指没有子节点的节点
示例1:
input:root = [3, 9, 20, null, null, 15, 7]
output:2
示例2:
input:root = [2, null, 3, null, 4, null, 5, null, 6]
output:5
方法1:深度优先搜索
解析:
使用深度优先搜索的方法,遍历整棵树,记录最小深度
对于每一个非叶子节点,只需要分别计算其左右子树的最小叶子节点深度。这样就将一个大问题转化为了小问题,可以递归地解决该问题
Java实现代码
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
int min_depth = Integer.MAX_VALUE;
if (root.left != null) {
min_depth = Math.min(minDepth(root.left), min_depth);
}
if (root.right != null) {
min_depth = Math.min(minDepth(root.right), min_depth);