mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 0501.二叉搜索树中的众数.md
java的暴力解法(map记录频率)
This commit is contained in:
@ -345,6 +345,40 @@ public:
|
|||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
|
||||||
|
暴力法
|
||||||
|
```java
|
||||||
|
class Solution {
|
||||||
|
public int[] findMode(FindModeInBinarySearchTree.TreeNode root) {
|
||||||
|
Map<Integer, Integer> map = new HashMap<>();
|
||||||
|
List<Integer> list = new ArrayList<>();
|
||||||
|
if (root == null) return list.stream().mapToInt(Integer::intValue).toArray();
|
||||||
|
// 获得频率 Map
|
||||||
|
searchBST(root, map);
|
||||||
|
List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream()
|
||||||
|
.sorted((c1, c2) -> c2.getValue().compareTo(c1.getValue()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
list.add(mapList.get(0).getKey());
|
||||||
|
// 把频率最高的加入 list
|
||||||
|
for (int i = 1; i < mapList.size(); i++) {
|
||||||
|
if (mapList.get(i).getValue() == mapList.get(i - 1).getValue()) {
|
||||||
|
list.add(mapList.get(i).getKey());
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return list.stream().mapToInt(Integer::intValue).toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
void searchBST(FindModeInBinarySearchTree.TreeNode curr, Map<Integer, Integer> map) {
|
||||||
|
if (curr == null) return;
|
||||||
|
map.put(curr.val, map.getOrDefault(curr.val, 0) + 1);
|
||||||
|
searchBST(curr.left, map);
|
||||||
|
searchBST(curr.right, map);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
```Java
|
```Java
|
||||||
class Solution {
|
class Solution {
|
||||||
ArrayList<Integer> resList;
|
ArrayList<Integer> resList;
|
||||||
|
Reference in New Issue
Block a user