2
public int[] findMode(TreeNode root) {3
if (root == null) return new int[0];4
Map<Integer, Integer> map =7
Integer>(); // we are taking map to count each and every value of the tree and the no of8
// times they occurs in the tree9
Queue<TreeNode> qu = new LinkedList<TreeNode>(); // to itereate over the tree12
Integer>(); // to save our result into a dynamic arraylist then will convert into static13
// array for return it14
qu.add(root); // add the first root node into queue to iterate over the tree15
while (!qu.isEmpty()) {16
TreeNode tmp = qu.poll(); // we poll out the node which is last inputed to the queue18
tmp.val)) { // we are checking through the map wheather the value this node have already19
// stored into the map or not23
+ 1); // the value is already stored then we just increase the count by 125
map.put(tmp.val, 1); // if the value is unique then we store it to the map with the count 129
tmp.left); // this way we are checking wheather left node has any value or not respect30
// to the current poped element of queue31
if (tmp.right != null)32
qu.add(tmp.right); // the same thing of the above just this is for right node of respective36
Integer.MIN_VALUE; // we are taking it because of requirement to identify highest no of37
// repeated node available in this tree39
map.keySet()) { // we are using keySet() for iterating over the map here key is differernt40
// nodes and value is the no of count they have in this tree42
> max) { // if anything we find have greater value then previous maximum no of node like 243
// 2 2 - value 3, 3 3 3 3 - value 4 so now 4 is the maximum now44
list.clear(); // just to clear previous data that are stored into that list45
max = map.get(key); // now max will replaced by the new no of count of a node46
list.add(key); // we are adding the key which has most no of count49
key)) { // if we found another node which also has present maximum no of node count in51
list.add(key); // we are also adding those key54
// now we just create an array transfer hole data that arraylist has and then return55
int[] res = new int[list.size()];56
for (int i = 0; i < list.size(); i++) {