LeetCode 501. 二叉搜索树中的众数 java题解

https://leetcode.cn/problems/find-mode-in-binary-search-tree/description/

class Solution {
    int count=0;
    int maxCount=0;
    TreeNode pre=null;
    ArrayList<Integer> res=new ArrayList<>();
    public int[] findMode(TreeNode root) {
        find(root);
        int[] r=new int[res.size()];
        for(int i=0;i<res.size();i++){
            r[i]=res.get(i);
        }
        return r;
    }
    //中序遍历保证有序
    public void find(TreeNode node){
        if(node==null) return;
        find(node.left);


        //处理node
        if(pre!=null){
            if(pre.val==node.val){
                count++;//在前面的基础上+1
            }
            else{
                count=1;//直接就只计算自己
            }
            if(count==maxCount){
                //如果等于之前的众数次数,说明这个也是另一个众数
                res.add(node.val);//加上自己
            }
            if(count>maxCount){//如果比之前的众数大
                maxCount=count;
                res.clear();//清空之前的结果
                res.add(node.val);//加上自己
            }
        }
        else{//前面没有节点,这是第一个节点
            count=1;
            maxCount=count;
            res.add(node.val);//当前节点,是一个众数
        }

        pre=node;
        find(node.right);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值