Merge branch 'master' of github.com:youngyangyang04/leetcode-master

This commit is contained in:
programmercarl
2022-06-27 09:59:01 +08:00
35 changed files with 1205 additions and 83 deletions

View File

@@ -488,6 +488,46 @@ 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
}
}
```
rust:
```rust
impl Solution {
@@ -550,6 +590,7 @@ impl Solution {
}
min_depth
}
```
-----------------------