Java Solution using a hash map and a global variable


  • 0
    D
    public class Solution {
        Map<Integer, Integer> map = new HashMap<>();
        int max_count = 0;
        
        public int[] findFrequentTreeSum(TreeNode root) {
            helper(root);
            
            Set<Map.Entry<Integer, Integer>> set = map.entrySet();
            
            List<Integer> list = new ArrayList<>();
            
            for (Map.Entry<Integer, Integer> item : set) {
                if (item.getValue() == max_count) list.add(item.getKey());
            }
            
            int[] res = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                res[i] = list.get(i);
            }
            
            return res;
        }
        
        private int helper(TreeNode root) {
            if (root == null) return 0;
            
            int left_sum = helper(root.left);
            int right_sum = helper(root.right);
            int sum = left_sum + right_sum + root.val;
            
            int count = map.getOrDefault(sum, 0) + 1;
            max_count = Math.max(count, max_count);
            map.put(sum, count);
            return sum;
        }
    }

Log in to reply
 

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