mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
添加 111:二叉树的最小深度 Java题解。
This commit is contained in:
@ -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 {
|
||||
/**
|
||||
|
Reference in New Issue
Block a user