6ms Java solution


  • 0
    M
    public int[] findMode(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Integer[] mpc = {0, null, 0};
        inorder(root, list, mpc);
        int[] res = new int[list.size()];
        for(int i = 0; i < list.size(); i++)
            res[i] = list.get(i);
            
        return res;    
    }
    
        static void inorder(TreeNode root, List<Integer> list, Integer[] mpc) {
        if(root == null) return;
        inorder(root.left, list, mpc);
        mpc[2] = mpc[1] != null && mpc[1].equals(root.val) ? mpc[2] + 1 : 1;
        mpc[1] = root.val;
        if(mpc[0].equals(mpc[2]))
            list.add(root.val);
        else if(mpc[0] < mpc[2]) {
            list.clear();
            list.add(root.val);
            mpc[0] = mpc[2];
        } 
        inorder(root.right, list, mpc);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.