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,重新放入众数,不需要额外空间,中序遍历即可完成。
本文介绍了一种使用中序遍历查找二叉搜索树中众数的方法。通过维护当前节点与前一个节点的关系,可以高效地找到众数。此方法无需额外空间,仅需一次遍历。
605

被折叠的 条评论
为什么被折叠?



