mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0501.二叉搜索树中的众数.md Scala版本
This commit is contained in:
@ -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关键字可以省略
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user