From 33ed3d980eecec6824fb5b9edad83d7b916c4142 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Thu, 19 May 2022 10:35:55 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86=20Scala?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index ab8f2e57..5afce73a 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -298,6 +298,31 @@ func levelOrder(_ root: TreeNode?) -> [[Int]] { return result } ``` +Scala: +```scala +// 102.二叉树的层序遍历 +object Solution { + import scala.collection.mutable + def levelOrder(root: TreeNode): List[List[Int]] = { + val res = mutable.ListBuffer[List[Int]]() + if (root == null) return res.toList + val queue = mutable.Queue[TreeNode]() // 声明一个队列 + queue.enqueue(root) // 把根节点加入queue + while (!queue.isEmpty) { + val tmp = mutable.ListBuffer[Int]() + val len = queue.size // 求出len的长度 + for (i <- 0 until len) { // 从0到当前队列长度的所有节点都加入到结果集 + val curNode = queue.dequeue() + tmp.append(curNode.value) + if (curNode.left != null) queue.enqueue(curNode.left) + if (curNode.right != null) queue.enqueue(curNode.right) + } + res.append(tmp.toList) + } + res.toList + } +} +``` **此时我们就掌握了二叉树的层序遍历了,那么如下九道力扣上的题目,只需要修改模板的两三行代码(不能再多了),便可打倒!**