mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 429.N叉树的层序遍历 Scala版本
This commit is contained in:
@ -1274,6 +1274,34 @@ func levelOrder(_ root: Node?) -> [[Int]] {
|
||||
}
|
||||
```
|
||||
|
||||
Scala:
|
||||
```scala
|
||||
// 429.N叉树的层序遍历
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def levelOrder(root: Node): List[List[Int]] = {
|
||||
val res = mutable.ListBuffer[List[Int]]()
|
||||
if (root == null) return res.toList
|
||||
val queue = mutable.Queue[Node]()
|
||||
queue.enqueue(root) // 根节点入队
|
||||
while (!queue.isEmpty) {
|
||||
val tmp = mutable.ListBuffer[Int]() // 存储每层节点
|
||||
val len = queue.size
|
||||
for (i <- 0 until len) {
|
||||
val curNode = queue.dequeue()
|
||||
tmp.append(curNode.value) // 将该节点的值加入tmp
|
||||
// 循环遍历该节点的子节点,加入队列
|
||||
for (child <- curNode.children) {
|
||||
queue.enqueue(child)
|
||||
}
|
||||
}
|
||||
res.append(tmp.toList) // 将该层的节点放到结果集
|
||||
}
|
||||
res.toList
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
# 515.在每个树行中找最大值
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/)
|
||||
|
Reference in New Issue
Block a user