From 3a7afacdeb785d271dbd57c236c2bd344a88b343 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sat, 21 May 2022 17:18:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200111.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6.md=20Sca?= =?UTF-8?q?la=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0111.二叉树的最小深度.md | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index 224caa5e..a7eb913e 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -488,5 +488,44 @@ func minDepth(_ root: TreeNode?) -> Int { } ``` +## Scala + +递归法: +```scala +object Solution { + def minDepth(root: TreeNode): Int = { + if (root == null) return 0 + if (root.left == null && root.right != null) return 1 + minDepth(root.right) + if (root.left != null && root.right == null) return 1 + minDepth(root.left) + // 如果两侧都不为空,则取最小值,return关键字可以省略 + 1 + math.min(minDepth(root.left), minDepth(root.right)) + } +} +``` + +迭代法: +```scala +object Solution { + import scala.collection.mutable + def minDepth(root: TreeNode): Int = { + if (root == null) return 0 + var depth = 0 + val queue = mutable.Queue[TreeNode]() + queue.enqueue(root) + while (!queue.isEmpty) { + depth += 1 + val len = queue.size + for (i <- 0 until len) { + val curNode = queue.dequeue() + if (curNode.left != null) queue.enqueue(curNode.left) + if (curNode.right != null) queue.enqueue(curNode.right) + if (curNode.left == null && curNode.right == null) return depth + } + } + depth + } +} +``` + -----------------------