class Solution {
int max = 0;
ArrayList<Integer> ans = new ArrayList<>();
int curmax = 1;
TreeNode pre;
TreeNode cur;
public int[] findMode(TreeNode root) {
dfs(root);
int[] res = new int[ans.size()];
for(int i = 0; i < res.length;i++){
res[i] = ans.get(i);
}
return res;
}
public void dfs(TreeNode root){
if(root == null) return;
dfs(root.left);
cur = root;
if(pre != null){
if(cur.val == pre.val) curmax++;
else curmax = 1;
}
pre = cur;
if(max < curmax){
ans.clear();
ans.add(cur.val);
max = curmax;
}else if(max == curmax){
ans.add(cur.val);
}
dfs(root.right);
}
}
二叉搜索树用中序遍历,利用前后指针来记录是否相等,相等计数器+1,比较历史最大众数,如果相等就在ans里加一个元素,如果出现更大的众数,则清空ans,重新放入众数,不需要额外空间,中序遍历即可完成。