leetcode-501. 二叉搜索树中的众数

原始思路

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
Map<Integer, Integer> map = new HashMap<>();
public int[] findMode(TreeNode root) {
if (root == null) {
return new int[]{};
}

dfs(root);

//记录最大值
int max = Integer.MIN_VALUE;
for(Map.Entry<Integer, Integer> entry: map.entrySet()){
max = Math.max(max, entry.getValue());
}

List<Integer> list = new ArrayList<>();
for(Map.Entry<Integer, Integer> entry: map.entrySet()){
if (entry.getValue() == max){
list.add(entry.getKey());
}
}

int[] arr = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
arr[i] = list.get(i);
}
return arr;
}

public void dfs(TreeNode root){
if (root.left != null) {
dfs(root.left);
}

if (root != null) {
if (map.containsKey(root.val)){
map.put(root.val, map.get(root.val) + 1);
}else {
map.put(root.val, 1);
}
}

if (root.right != null) {
dfs(root.right);
}
}
}