You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Map<Integer, Integer> map = newHashMap<Integer, Integer>(); //we are taking map to count each and every value of the tree and the no of times they occurs in the tree
7
+
Queue<TreeNode> qu = newLinkedList<TreeNode>(); // to itereate over the tree
8
+
List<Integer> list = newArrayList<Integer>(); //to save our result into a dynamic arraylist then will convert into static array for return it
9
+
qu.add(root); // add the first root node into queue to iterate over the tree
10
+
while(!qu.isEmpty()) {
11
+
TreeNodetmp = qu.poll(); //we poll out the node which is last inputed to the queue
12
+
if(map.containsKey(tmp.val)) { //we are checking through the map wheather the value this node have already stored into the map or not
13
+
map.put(tmp.val, map.get(tmp.val)+1); //the value is already stored then we just increase the count by 1
13
14
}
14
-
}
15
-
for(inti = 0; i < al.size(); i++){
16
-
intvalue = al1.get(i);
17
-
if(value == max){
18
-
al2.add(al.get(i));
15
+
else {
16
+
map.put(tmp.val, 1); //if the value is unique then we store it to the map with the count 1
19
17
}
18
+
if(tmp.left!=null) qu.add(tmp.left); //this way we are checking wheather left node has any value or not respect to the current poped element of queue
19
+
if(tmp.right!=null) qu.add(tmp.right); //the same thing of the above just this is for right node of respective poped out node
publicvoidfunc( HashMap<Integer,Integer> hm , TreeNoderoot) //traverse by preorder
31
-
{
32
-
33
-
if(root != null){
34
-
intvalue = root.val;
35
-
36
-
if(hm.containsKey(value)){
37
-
hm.put(value,1 + hm.get(value));
38
-
21
+
intmax = Integer.MIN_VALUE; //we are taking it because of requirement to identify highest no of repeated node available in this tree
22
+
for(Integerkey : map.keySet()) { //we are using keySet() for iterating over the map here key is differernt nodes and value is the no of count they have in this tree
23
+
if(map.get(key)>max) { //if anything we find have greater value then previous maximum no of node like 2 2 2 - value 3, 3 3 3 3 - value 4 so now 4 is the maximum now
24
+
list.clear(); //just to clear previous data that are stored into that list
25
+
max = map.get(key); //now max will replaced by the new no of count of a node
26
+
list.add(key); //we are adding the key which has most no of count
27
+
}
28
+
elseif(max==map.get(key)) { //if we found another node which also has present maximum no of node count in the tree
29
+
list.add(key); //we are also adding those key
30
+
}
39
31
}
40
-
else
41
-
hm.put(value,1);
42
-
43
-
func(hm,root.left);
44
-
func(hm,root.right);
32
+
//now we just create an array transfer hole data that arraylist has and then return
0 commit comments