diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index 8b9d92e6..c4e55a07 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -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 { /**