mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
Merge pull request #1354 from wzqwtt/tree05
添加(104.二叉树的最大深度、111.二叉树的最小深度)Scala版本
This commit is contained in:
@ -2451,6 +2451,30 @@ func maxDepth(_ root: TreeNode?) -> Int {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Scala:
|
||||||
|
```scala
|
||||||
|
// 104.二叉树的最大深度
|
||||||
|
object Solution {
|
||||||
|
import scala.collection.mutable
|
||||||
|
def maxDepth(root: TreeNode): Int = {
|
||||||
|
if (root == null) return 0
|
||||||
|
val queue = mutable.Queue[TreeNode]()
|
||||||
|
queue.enqueue(root)
|
||||||
|
var depth = 0
|
||||||
|
while (!queue.isEmpty) {
|
||||||
|
val len = queue.length
|
||||||
|
depth += 1
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
depth
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
# 111.二叉树的最小深度
|
# 111.二叉树的最小深度
|
||||||
|
|
||||||
[力扣题目链接](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/)
|
[力扣题目链接](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/)
|
||||||
@ -2670,6 +2694,30 @@ func minDepth(_ root: TreeNode?) -> Int {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Scala:
|
||||||
|
```scala
|
||||||
|
// 111.二叉树的最小深度
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
# 总结
|
# 总结
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user