mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0111.二叉树的最小深度.md Scala版本
This commit is contained in:
@ -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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user