forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_501.java
93 lines (83 loc) · 2.95 KB
/
_501.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
public class _501 {
public static class Solution1 {
public int[] findMode(TreeNode root) {
int[] result = new int[]{};
Map<Integer, Integer> map = new HashMap();
if (root == null) {
return result;
}
List<Integer> list = bfs(root, map);
result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
private List<Integer> bfs(TreeNode root, Map<Integer, Integer> map) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode treeNode = queue.poll();
if (treeNode.left != null) {
queue.offer(treeNode.left);
}
if (treeNode.right != null) {
queue.offer(treeNode.right);
}
map.put(treeNode.val, map.getOrDefault(treeNode.val, 0) + 1);
}
}
int highestFrequency = 0;
List<Integer> list = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > highestFrequency) {
highestFrequency = entry.getValue();
list.clear();
list.add(entry.getKey());
} else if (entry.getValue() == highestFrequency) {
list.add(entry.getKey());
}
}
return list;
}
}
public static class Solution2 {
public int[] findMode(TreeNode root) {
Map<Integer, Integer> map = new HashMap<>();
dfs(root, map);
int modeCount = 0;
for (int key : map.keySet()) {
modeCount = Math.max(modeCount, map.get(key));
}
List<Integer> mode = new ArrayList<>();
for (int key : map.keySet()) {
if (map.get(key) == modeCount) {
mode.add(key);
}
}
int[] result = new int[mode.size()];
for (int i = 0; i < mode.size(); i++) {
result[i] = mode.get(i);
}
return result;
}
private void dfs(TreeNode root, Map<Integer, Integer> map) {
if (root == null) {
return;
}
dfs(root.left, map);
map.put(root.val, map.getOrDefault(root.val, 0) + 1);
dfs(root.right, map);
}
}
}