-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFindModeinBinarySearchTree501.java
More file actions
40 lines (33 loc) · 1016 Bytes
/
FindModeinBinarySearchTree501.java
File metadata and controls
40 lines (33 loc) · 1016 Bytes
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
import java.util.ArrayList;
import java.util.List;
public class FindModeinBinarySearchTree501 {
private int currentVal;
private int currentCount = 0;
private int maxCount = 0;
private List<Integer> modes = new ArrayList<>();
public int[] findMode(TreeNode root){
InOrderTraversal(root);
int[] result = new int[modes.size()];
for(int i = 0; i < modes.size(); i++){
result[i] = modes.get(i);
}
return result;
}
private void InOrderTraversal(TreeNode node){
if(node == null){
return;
}
InOrderTraversal((node.left));
currentCount = (node.val == currentVal) ? currentCount + 1 : 1;
if(currentCount == maxCount){
modes.add(node.val);
}
else if(currentCount > maxCount){
maxCount = currentCount;
modes.clear();
modes.add(node.val);
}
currentVal = node.val;
InOrderTraversal(node.right);
}
}