Find Mode in Binary Search Tree LeetCode solution in Java

1
class Solution {
2
public int[] findMode(TreeNode root) {
3
if (root == null) return new int[0];
4
Map<Integer, Integer> map =
5
new HashMap<
6
Integer,
7
Integer>(); // we are taking map to count each and every value of the tree and the no of
8
// times they occurs in the tree
9
Queue<TreeNode> qu = new LinkedList<TreeNode>(); // to itereate over the tree
10
List<Integer> list =
11
new ArrayList<
12
Integer>(); // to save our result into a dynamic arraylist then will convert into static
13
// array for return it
14
qu.add(root); // add the first root node into queue to iterate over the tree
15
while (!qu.isEmpty()) {
16
TreeNode tmp = qu.poll(); // we poll out the node which is last inputed to the queue
17
if (map.containsKey(
18
tmp.val)) { // we are checking through the map wheather the value this node have already
19
// stored into the map or not
20
map.put(
21
tmp.val,
22
map.get(tmp.val)
23
+ 1); // the value is already stored then we just increase the count by 1
24
} else {
25
map.put(tmp.val, 1); // if the value is unique then we store it to the map with the count 1
26
}
27
if (tmp.left != null)
28
qu.add(
29
tmp.left); // this way we are checking wheather left node has any value or not respect
30
// to the current poped element of queue
31
if (tmp.right != null)
32
qu.add(tmp.right); // the same thing of the above just this is for right node of respective
33
// poped out node
34
}
35
int max =
36
Integer.MIN_VALUE; // we are taking it because of requirement to identify highest no of
37
// repeated node available in this tree
38
for (Integer key :
39
map.keySet()) { // we are using keySet() for iterating over the map here key is differernt
40
// nodes and value is the no of count they have in this tree
41
if (map.get(key)
42
> max) { // if anything we find have greater value then previous maximum no of node like 2
43
// 2 2 - value 3, 3 3 3 3 - value 4 so now 4 is the maximum now
44
list.clear(); // just to clear previous data that are stored into that list
45
max = map.get(key); // now max will replaced by the new no of count of a node
46
list.add(key); // we are adding the key which has most no of count
47
} else if (max
48
== map.get(
49
key)) { // if we found another node which also has present maximum no of node count in
50
// the tree
51
list.add(key); // we are also adding those key
52
}
53
}
54
// now we just create an array transfer hole data that arraylist has and then return
55
int[] res = new int[list.size()];
56
for (int i = 0; i < list.size(); i++) {
57
res[i] = list.get(i);
58
}
59
return res;
60
}
61
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0