-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathFindModeinBST.java
46 lines (38 loc) · 1.09 KB
/
FindModeinBST.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
package problems.easy;
import problems.utils.TreeNode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by sherxon on 1/28/17.
*/
public class FindModeinBST {
int max = 1;
public int[] findMode(TreeNode root) {
if (root == null) return new int[0];
Map<Integer, Integer> map = new HashMap<>();
find(root, map);
List<Integer> list = new ArrayList<>();
for (Integer integer : map.keySet()) {
if (map.get(integer) == max) list.add(integer);
}
int[] a = new int[list.size()];
int i = 0;
for (Integer integer : list) {
a[i++] = integer;
}
return a;
}
private void find(TreeNode root, Map<Integer, Integer> map) {
if (root == null) return;
if (map.containsKey(root.val)) {
int val = map.get(root.val) + 1;
map.put(root.val, val);
max = Math.max(max, val);
} else
map.put(root.val, 1);
find(root.left, map);
find(root.right, map);
}
}