diff --git "a/problems/0501.\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\274\227\346\225\260.md" "b/problems/0501.\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\274\227\346\225\260.md" index d2326d6703..66be790fbb 100644 --- "a/problems/0501.\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\274\227\346\225\260.md" +++ "b/problems/0501.\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\274\227\346\225\260.md" @@ -345,6 +345,40 @@ public: Java: +暴力法 +```java +class Solution { + public int[] findMode(FindModeInBinarySearchTree.TreeNode root) { + Map map = new HashMap<>(); + List list = new ArrayList<>(); + if (root == null) return list.stream().mapToInt(Integer::intValue).toArray(); + // 获得频率 Map + searchBST(root, map); + List> 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 map) { + if (curr == null) return; + map.put(curr.val, map.getOrDefault(curr.val, 0) + 1); + searchBST(curr.left, map); + searchBST(curr.right, map); + } + +} +``` + ```Java class Solution { ArrayList resList;