-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode501_modeBST.java
More file actions
71 lines (57 loc) · 1.96 KB
/
Copy pathleetcode501_modeBST.java
File metadata and controls
71 lines (57 loc) · 1.96 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
62
63
64
65
66
67
68
69
70
71
import java.util.*;
public class leetcode501_modeBST {
HashMap<Integer,Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
int maxValue = Integer.MIN_VALUE;
public void preOrderTraversal(TreeNode node){
if(node == null)
return;
if(map.get(node.val) == null){
map.put(node.val, 1);
}
else{
map.put(node.val,map.get(node.val) + 1);
}
preOrderTraversal(node.left);
preOrderTraversal(node.right);
}
public int[] findMode(TreeNode root) {
int[] arr = new int[0];
if(root == null)
return arr;
preOrderTraversal(root);
//Iterate through the hashmap to find max value
Iterator iterator1 = map.entrySet().iterator();
while(iterator1.hasNext()){
Map.Entry mapElement = (Map.Entry)iterator1.next();
int val = (int)mapElement.getValue();
if(val > maxValue)
maxValue = val;
}
//Iterating through the HashMap to get all the elements with maxVal
Iterator iterator2 = map.entrySet().iterator();
while(iterator2.hasNext()){
Map.Entry mapElement = (Map.Entry)iterator2.next();
int val = (int)mapElement.getValue();
if(val == maxValue)
list.add((int)mapElement.getKey());
}
//Shifting elements from the arraylist to int array
int[] result = new int[list.size()];
for(int i=0;i<list.size();i++){
result[i] = list.get(i);
}
return result;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = null;
root.right = new TreeNode(2);
root.right.left = new TreeNode(2);
leetcode501_modeBST obj = new leetcode501_modeBST();
int[] res = obj.findMode(root);
for(int i: res){
System.out.println(i);
}
}
}