From 80301657b305bcbd614d5294b1d483d31419755f Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Thu, 19 May 2022 12:29:12 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20515.=E5=9C=A8=E6=AF=8F?= =?UTF-8?q?=E4=B8=AA=E6=A0=91=E8=A1=8C=E4=B8=AD=E6=89=BE=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E5=80=BC=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 26 +++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index ab8f2e57..db27c73d 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1433,6 +1433,32 @@ func largestValues(_ root: TreeNode?) -> [Int] { } ``` +Scala: +```scala +// 515.在每个树行中找最大值 +object Solution { + import scala.collection.mutable + def largestValues(root: TreeNode): List[Int] = { + val res = mutable.ListBuffer[Int]() + if (root == null) return res.toList + val queue = mutable.Queue[TreeNode]() + queue.enqueue(root) + while (!queue.isEmpty) { + var max = Int.MinValue // 初始化max为系统最小值 + val len = queue.size + for (i <- 0 until len) { + val curNode = queue.dequeue() + max = math.max(max, curNode.value) // 对比求解最大值 + if (curNode.left != null) queue.enqueue(curNode.left) + if (curNode.right != null) queue.enqueue(curNode.right) + } + res.append(max) // 将最大值放入结果集 + } + res.toList + } +} +``` + # 116.填充每个节点的下一个右侧节点指针 [力扣题目链接](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/)