From 770c138a9aeb1340ec0721fefc8686d9aedb9f8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=91=AB?= <2507932331@qq.com> Date: Tue, 24 Oct 2023 17:06:10 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20111=EF=BC=9A=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6?= =?UTF-8?q?=20Java=E9=A2=98=E8=A7=A3=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0111.二叉树的最小深度.md | 28 +++++++++++++++++++++++ 1 file changed, 28 insertions(+) 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 { /**