-
Notifications
You must be signed in to change notification settings - Fork 16
/
FindModeInBinarySearchTree.java
50 lines (45 loc) · 1.33 KB
/
FindModeInBinarySearchTree.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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FindModeInBinarySearchTree {
private static TreeNode previous;
private static int count = 1;
private static int mode = 0;
public static int[] findMode(TreeNode root) {
if (root == null) {
return new int[0];
}
List<Integer> modes = new ArrayList<>();
findMode(root, modes);
int[] result = new int[modes.size()];
for(int index = 0 ; index < modes.size() ; index++) {
result[index] = modes.get(index);
}
previous = null;
count = 1;
mode = 0;
return result;
}
private static void findMode(TreeNode root, List<Integer> modes) {
if (root == null) {
return;
}
findMode(root.left, modes);
if (previous != null) {
count = root.val == previous.val ? count + 1 : 1;
}
if (count > mode) {
mode = count;
modes.clear();
modes.add(root.val);
} else if (count == mode) {
modes.add(root.val);
}
previous = root;
findMode(root.right, modes);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(0);
System.out.println(Arrays.toString(findMode(root)));
}
}