力扣【501. 二叉搜索树中的众数】Java题解

题目要求不使用额外空间。

思路:

可以两次遍历,第一次找到众数的节点个数,第二次找出众数数组。
但我们可以把这两次遍历改为一次遍历,就是找众数的节点个数时同时去更新众数数组,当maxCount等于count时,追加当前节点的值到众数数组中;当maxCount大于count时,将结果数组清空后加入当前节点。

代码:

class Solution {
    int maxCount=0; //目前众数节点的个数
    int count;  //目前节点的个数
    ArrayList<Integer> list=new ArrayList<>(); //存放结果
    TreeNode preNode; //前一个节点,一开始没有
    public int[] findMode(TreeNode root) {
        find(root);
        //将集合转换为数组
        int[] res = new int[list.size()];
        for(int i=0;i<list.size();i++){
            res[i] = list.get(i);
        }
        return res;
    }
    public void find(TreeNode root) {
        //非空判断
        if(root == null) return;
        //遍历左子树
        find(root.left);
        //当前节点个数判断
        if(preNode!=null && preNode.val == root.val){
            count++;
        }else{
            count = 1;
        }
        //判断是否是众数,是则更新结果集合
        if(count == maxCount){
            list.add(root.val);
        }else if(count > maxCount){
            list = new ArrayList<>();
            list.add(root.val);
            maxCount = count;
        }
        preNode = root;
        //遍历右子树
        find(root.right);
    }
}

你可能感兴趣的:(leetcode,java,算法)