Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit15582ef

Browse files
Merge pull requestyoungyangyang04#453 from daniel1n/patch-2
Update 0501.二叉搜索树中的众数.md
2 parents0f38eb9 +383c9cb commit15582ef

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

‎problems/0501.二叉搜索树中的众数.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,40 @@ public:
345345

346346
Java:
347347

348+
暴力法
349+
```java
350+
classSolution {
351+
public int[] findMode(FindModeInBinarySearchTree.TreeNode root) {
352+
Map<Integer, Integer> map = new HashMap<>();
353+
List<Integer> list = new ArrayList<>();
354+
if (root == null) return list.stream().mapToInt(Integer::intValue).toArray();
355+
// 获得频率 Map
356+
searchBST(root, map);
357+
List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream()
358+
.sorted((c1, c2) -> c2.getValue().compareTo(c1.getValue()))
359+
.collect(Collectors.toList());
360+
list.add(mapList.get(0).getKey());
361+
// 把频率最高的加入 list
362+
for (int i = 1; i < mapList.size(); i++) {
363+
if (mapList.get(i).getValue() == mapList.get(i - 1).getValue()) {
364+
list.add(mapList.get(i).getKey());
365+
} else {
366+
break;
367+
}
368+
}
369+
return list.stream().mapToInt(Integer::intValue).toArray();
370+
}
371+
372+
void searchBST(FindModeInBinarySearchTree.TreeNode curr, Map<Integer, Integer> map) {
373+
if (curr == null) return;
374+
map.put(curr.val, map.getOrDefault(curr.val, 0) + 1);
375+
searchBST(curr.left, map);
376+
searchBST(curr.right, map);
377+
}
378+
379+
}
380+
```
381+
348382
```Java
349383
classSolution {
350384
ArrayList<Integer> resList;

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp