Merge pull request #2317 from xiaoxinxing66/master

添加 0111.二叉树的最小深度 Java题解
This commit is contained in:
程序员Carl
2023-10-25 11:17:07 +08:00
committed by GitHub

View File

@ -268,6 +268,34 @@ class Solution {
}
```
```java
class Solution {
/**
* 递归法(思路来自二叉树最大深度的递归法)
* 该题求最小深度,最小深度为根节点到叶子节点的深度,所以在迭代到每个叶子节点时更新最小值。
*/
int depth = 0;
// 定义最小深度,初始化最大值
int minDepth = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
dep(root);
return minDepth == Integer.MAX_VALUE ? 0 : minDepth;
}
void dep(TreeNode root){
if(root == null) return ;
// 递归开始,深度增加
depth++;
dep(root.left);
dep(root.right);
// 该位置表示递归到叶子节点了需要更新最小深度minDepth
if(root.left == null && root.right == null)
minDepth = Math.min(minDepth , depth);
// 递归结束,深度减小
depth--;
}
}
```
```Java
class Solution {
/**