/** * Definition for a binary tree node. * public class TreeNode { *? ? int val; *? ? TreeNode left; *? ? TreeNode right; *? ? TreeNode(int x) { val = x; } * } */public class Solution {? ? HashMapmap = new HashMap();? ? ? ? ? public int[] findMode(TreeNode root) {? ? ? ? if(root == null){? ? ? ? ? ? return new int[0];? ? ? ? }? ? ? ? inOrder(root);? ? ? ? Iterator it = map.entrySet().iterator();? ? ? ? int max = Integer.MIN_VALUE;? ? ? ? ArrayListlist = new ArrayList();? ? ? ? for(Map.Entryentry: map.entrySet()){? ? ? ? ? ? Integer key = entry.getKey();? ? ? ? ? ? Integer value = entry.getValue();? ? ? ? ? ? max = Math.max(max,(int)value);? ? ? ? }? ? ? ? for(Map.Entryi: map.entrySet()){
Integer value = i.getValue();
Integer key = i.getKey();
if(max ==(int)value){
list.add(key);
}
}
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++){
array[i] = list.get(i);
}
return array;
}
private void inOrder(TreeNode root){
if(root == null){
return;
}
if(!map.containsKey(root.val)){
map.put(root.val, 1);
//size = Math
}else{
int teemp = map.get(root.val) + 1;
map.put(root.val, teemp);
}
inOrder(root.left);
inOrder(root.right);
}
}