Simple Java O(1) space solution[Beats 99.5% Java Solutions]


  • 0
    R
    public class Solution {
        private int max;
        private long prev;
        private int count;
        public int[] findMode(TreeNode root) {
            max = 0;
            prev = Integer.MAX_VALUE + 1L;
            count = 0;
            List<Integer> list = new ArrayList<>();
            modeHelper(root, list);
            if(count >= max) {
                if(count > max) {
                    list.clear();
                    max = count;
                }
                if(prev <= Integer.MAX_VALUE) list.add((int) prev);
            }
            int[] result = new int[list.size()];
            for(int i = 0; i < list.size(); ++i) {
                result[i] = list.get(i);
            }
            return result;
        }
        
        private void modeHelper(TreeNode node, List<Integer> list) {
            if(node == null) return;
            
            modeHelper(node.left, list);
            if(prev == node.val) {
                count++;
            }else {
                 if(count >= max) {
                    if(count > max) {
                        list.clear();
                        max = count;
                    }
                    if(prev <= Integer.MAX_VALUE) list.add((int) prev);
                }
                prev = node.val;
                count = 1;
            }
            modeHelper(node.right, list);
        }
    }
    
    

Log in to reply
 

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