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);
    }
}

你可能感兴趣的:(LeetCode,leetcode,java,算法,二叉树)