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

class Solution {
    //定义一个众数的最大数量值
    int maxCount = 0;
    //定义一个当前众数节点的数量
    int count = 0;
    //定义当前众数节点的值
    int cur = 0;
    //存放众数的集合
    List<Integer> list = new ArrayList<>();
    public int[] findMode(TreeNode root) {
        inOrderTree(root);
        int[] res = new int[list.size()];
        for(int i = 0;i<list.size();i++){
            res[i] = list.get(i);
        }
        return res;
    }
    public void inOrderTree(TreeNode root){
        //边界条件
        if(root == null) return;
        //先遍历左子树
        inOrderTree(root.left);
        //逻辑判断,找出众数
        //如果节点的值等于cur,count+1
        if(root.val == cur){
            count++;
        }else{//如果不等于,说明是新的值,此时更新cur,count
            cur = root.val;
            count = 1;
        }
        
        //如果count等于 maxCount,说明当前节点的数量 等于最大的数量
        if(count == maxCount){
            list.add(root.val);
        }else if(count > maxCount){//说明当前节点的数量是最多的,应该把list清空,把最多的节点放入,同时更新maxCount
            list.clear();
            list.add(root.val);
            maxCount = count;
        } 
        //遍历右子树
        inOrderTree(root.right);

    }
}
原文地址:https://www.cnblogs.com/peanut-zh/p/13888724.html