501. 二叉搜索树中的众数

501. 二叉搜索树中的众数

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,重新放入众数,不需要额外空间,中序遍历即可完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值