Java 8ms O(n) Time O(n) Space

  • 1
        int highestCount, numWithHighestCount, i;
        Map<Integer, Integer> valToNumberAppearance  = new HashMap<Integer, Integer>();
        public int[] findMode(TreeNode root) {
            int[] res = new int[numWithHighestCount];
            for (Map.Entry<Integer, Integer> entry : valToNumberAppearance.entrySet()) 
                if (entry.getValue() == highestCount) res[i++] = entry.getKey();
            return res;
        public void populateMap(TreeNode cur) {
            Integer curOcurrences = valToNumberAppearance.getOrDefault(cur.val, 0);
            valToNumberAppearance.put(cur.val, ++curOcurrences);
            if (curOcurrences > highestCount) {
                highestCount = curOcurrences;
                numWithHighestCount = 1;
            else if (curOcurrences == highestCount) numWithHighestCount++;
            if (cur.left != null) populateMap(cur.left);
            if (cur.right != null) populateMap(cur.right);

  • 0

    @compton_scatter Your code fails for when the input [ ] is empty. Adding a check for at the start of populateMap() for if (cur == null) return; will work fine.

Log in to reply

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