4ms Java solution beats 100% O(1) space(recursion stack space doesn't count)


  • 3

    Just simple inorder traversal, whenever current frequency for current number is bigger than max frequency, update the result.

    public class Solution {
        List<Integer> ans = new ArrayList<>();
        Integer pre;
        int maxFreq = 0, curFreq = 0;
        public int[] findMode(TreeNode root) {
            traverse(root);
            int[] res = new int[ans.size()];
            for (int i = 0; i < res.length; i++) res[i] = ans.get(i);
            return res;
        }
        
        private void traverse(TreeNode root) {
            if (root == null) {
                return;
            }
            //inorder traversal
            traverse(root.left);
            if (pre != null && root.val == pre) {
                curFreq++;
            } else {
                curFreq = 1;
            }
            if (curFreq == maxFreq) {
                ans.add(root.val);
            } else if (curFreq > maxFreq) {
                maxFreq = curFreq;
                ans = new ArrayList<>();
                ans.add(root.val);
            } 
    
            pre = root.val;
            traverse(root.right);
        }
    }
    

Log in to reply
 

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