From 779adf74cb1ec9b1f8b17db3cbf3d8fc3b88392f Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sat, 28 May 2022 14:53:40 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200501.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E4=BC=97=E6=95=B0?= =?UTF-8?q?.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0501.二叉搜索树中的众数.md | 71 +++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 9cb5d071..c08f68d9 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -9,7 +9,7 @@ # 501.二叉搜索树中的众数 -[力扣题目链接](https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/solution/) +[力扣题目链接](https://leetcode.cn/problems/find-mode-in-binary-search-tree/) 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 @@ -798,7 +798,76 @@ function findMode(root: TreeNode | null): number[] { }; ``` +## Scala +暴力: +```scala +object Solution { + // 导包 + import scala.collection.mutable // 集合包 + import scala.util.control.Breaks.{break, breakable} // 流程控制包 + def findMode(root: TreeNode): Array[Int] = { + var map = mutable.HashMap[Int, Int]() // 存储节点的值,和该值出现的次数 + def searchBST(curNode: TreeNode): Unit = { + if (curNode == null) return + var value = map.getOrElse(curNode.value, 0) + map.put(curNode.value, value + 1) + searchBST(curNode.left) + searchBST(curNode.right) + } + searchBST(root) // 前序遍历把每个节点的值加入到里面 + // 将map转换为list,随后根据元组的第二个值进行排序 + val list = map.toList.sortWith((map1, map2) => { + if (map1._2 > map2._2) true else false + }) + var res = mutable.ArrayBuffer[Int]() + res.append(list(0)._1) // 将第一个加入结果集 + breakable { + for (i <- 1 until list.size) { + // 如果值相同就加入结果集合,反之break + if (list(i)._2 == list(0)._2) res.append(list(i)._1) + else break + } + } + res.toArray // 最终返回res的Array格式,return关键字可以省略 + } +} +``` + +递归(利用二叉搜索树的性质): +```scala +object Solution { + import scala.collection.mutable + def findMode(root: TreeNode): Array[Int] = { + var maxCount = 0 // 最大频率 + var count = 0 // 统计频率 + var pre: TreeNode = null + var result = mutable.ArrayBuffer[Int]() + + def searchBST(cur: TreeNode): Unit = { + if (cur == null) return + searchBST(cur.left) + if (pre == null) count = 1 // 等于空置为1 + else if (pre.value == cur.value) count += 1 // 与上一个节点的值相同加1 + else count = 1 // 与上一个节点的值不同 + pre = cur + + // 如果和最大值相同,则放入结果集 + if (count == maxCount) result.append(cur.value) + + // 如果当前计数大于最大值频率,更新最大值,清空结果集 + if (count > maxCount) { + maxCount = count + result.clear() + result.append(cur.value) + } + searchBST(cur.right) + } + searchBST(root) + result.toArray // return关键字可以省略 + } +} +``` -----------------------