-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModeInBST.java
More file actions
61 lines (49 loc) · 1.5 KB
/
ModeInBST.java
File metadata and controls
61 lines (49 loc) · 1.5 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
57
58
59
60
61
package BinarySearchTrees;
import java.util.*;
public class ModeInBST {
public static int[] findMode(Node root) {
int maxStreak = 0;
int currStreak = 0;
int currNum = 0;
List<Integer> ans = new ArrayList<>();
Node curr = root;
while (curr != null) {
if (curr.left != null) {
// Find the friend
Node friend = curr.left;
while (friend.right != null) {
friend = friend.right;
}
friend.right = curr;
// Delete the edge after using it
Node left = curr.left;
curr.left = null;
curr = left;
} else {
// Handle the current node
int num = curr.val;
if (num == currNum) {
currStreak++;
} else {
currStreak = 1;
currNum = num;
}
if (currStreak > maxStreak) {
ans = new ArrayList<>();
maxStreak = currStreak;
}
if (currStreak == maxStreak) {
ans.add(num);
}
curr = curr.right;
}
}
int[] result = new int[ans.size()];
for (int i = 0; i < ans.size(); i++) {
result[i] = ans.get(i);
}
return result;
}
public static void main(String[] args) {
}
}