-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path501. Find Mode in Binary Search Tree.java
61 lines (49 loc) · 1.41 KB
/
501. Find Mode in Binary Search Tree.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int modeCount = 0;
private int curCount = 0;
private int previous = Integer.MIN_VALUE;
private ArrayList<Integer> ans;
// Keywords are: Binary Search Tree, Inorder Traversal!!! (O(1) space)
// However, a HashMap straightforward implementation is more likely (O(n) space)
public void helper(TreeNode root) {
if (root == null) return;
helper(root.left);
if (root.val != previous) {
curCount = 1;
} else {
curCount++;
}
if (curCount >= modeCount) {
if (curCount > modeCount) {
ans.clear();
}
modeCount = curCount;
ans.add(root.val);
}
previous = root.val;
helper(root.right);
}
int [] convert(ArrayList<Integer> ans) {
int[] out = new int[ans.size()];
int j = 0;
for (Integer i : ans) {
out[j++] = i;
}
return out;
}
public int[] findMode(TreeNode root) {
if (root == null) return new int[0];
this.ans = new ArrayList<>();
helper(root);
return convert(ans);
}
}