JAVA solution HashSet


  • 0
    C
    public class Solution {
        int count = 0;
        boolean isSetPre = false;
        int pre = 0;
        int max = 0;
        Set<Integer> set;
        public int[] findMode(TreeNode root) {
            if(root==null) return new int[0];
            traverse(root);
            return toInt(set);
        }
        
        private void traverse(TreeNode root) {
            if(root==null)return;
            traverse(root.left);
            if(!isSetPre || root.val != pre) {
                count = 1;
            } else {
                count ++;
            }
            if(count > max) {
                max = count;
                set = new HashSet<Integer>();
                set.add(root.val);
            } else if (count == max) {
                set.add(root.val);
            }
            pre = root.val;
            isSetPre = true;
            traverse(root.right);
        }
        
        public int[] toInt(Set<Integer> set) {
            int[] a = new int[set.size()];
            int i = 0;
            for (Integer val : set) a[i++] = val;
            return a;
        }
    }
    

Log in to reply
 

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