-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFindModeInBinarySearchTree.java
More file actions
56 lines (41 loc) · 1.59 KB
/
Copy pathFindModeInBinarySearchTree.java
File metadata and controls
56 lines (41 loc) · 1.59 KB
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
// Given a binary search tree (BST) with duplicates,
// find all the mode(s) (the most frequently occurred element) in the given BST.
// See: https://leetcode.com/problems/find-mode-in-binary-search-tree/
package leetcode.tree;
import static leetcode.util.tree.BinTreeUtil.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import leetcode.util.tree.TreeNode;
public class FindModeInBinarySearchTree {
public int[] findMode(TreeNode root) {
Map<Integer, Integer> map = new HashMap<>();
dfs(root, map);
List<Integer> modes = new ArrayList<>();
int maxModeValue = 1;
for (Map.Entry<Integer, Integer> pair : map.entrySet()) {
if (pair.getValue() > maxModeValue) {
maxModeValue = pair.getValue();
}
}
for (Map.Entry<Integer, Integer> pair : map.entrySet()) {
if (pair.getValue() == maxModeValue) {
modes.add(pair.getKey());
}
}
return modes.stream().mapToInt(i->i).toArray();
}
public void dfs(TreeNode root, Map<Integer, Integer> map) {
if (root == null) return;
map.put(root.val, map.getOrDefault(root.val, 0) + 1);
dfs(root.left, map);
dfs(root.right, map);
}
public static void main(String[] args) {
FindModeInBinarySearchTree sln = new FindModeInBinarySearchTree();
TreeNode t1 = initTree(1, null, 2, 2);
System.out.println(Arrays.toString(sln.findMode(t1)));
}
}