Java Straight forward solution

  • 1

    Using in order traversal to update mode value(s)

    public int[] findMode(TreeNode root) {
            if(root == null) return new int[0];
            List<Integer> res = new ArrayList<Integer>();
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            helper(res, root, map);
            HashSet<Integer> set = new HashSet<Integer>(res);
            int[] ret = new int[set.size()];
            Iterator it = set.iterator();
            int i = 0;
                ret[i ++] = (int);
            return ret;
        public void helper(List<Integer> res, TreeNode root, HashMap<Integer, Integer> map){
            if(root == null) return ;
            helper(res, root.left, map);
            map.put(root.val, map.getOrDefault(root.val, 0) + 1);
            if(res.size() == 0 || map.get(res.get(0)) == map.get(root.val)){
            }else if(map.get(root.val) > map.get(res.get(0))){
            helper(res, root.right, map);

    BTW, I think my solution is weird. There may be some redundancy inside. Any comments are welcome. Thanks.

Log in to reply

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