简单题基本套用经典的遍历模板都能解决,这题需要在递归的过程中统计一个数值的出现次数,若出现次数等于历史最大出现此时,则添加入数组中,若次数大于历史最大出现次数,则更新最大出现次数并清空数组中的旧值,添加新的数值。
class Solution {
ArrayList<Integer> res = new ArrayList<>();
int count = 1;
TreeNode pre;
int max = 1;
public int[] findMode(TreeNode root) {
dfs(root);
int[] a = new int[res.size()];
for(int i=0;i<res.size(); i++){
a[i] = res.get(i);
}
return a;
}
public void dfs(TreeNode root){
if(root == null)return;
dfs(root.left);
if(pre == null){
count=1;
res.add(root.val);
}else if(root.val == pre.val){
count++;
if(count == max){
res.add(root.val);
}
if(count>max){
max = count;
res.clear();
res.add(root.val);
}
}else if(root.val != pre.val){
count=1;
if(count == max)res.add(root.val);
}
pre = root;
dfs(root.right);
}
}