Simple Java Solution


  • 0
    S
    public class Solution {
        
        int max;
        
        public int[] findFrequentTreeSum(TreeNode root) {
            if(root == null) return new int[0];
            max = Integer.MIN_VALUE;
            Map<Integer, Integer> map = new HashMap<>();
            helper(root, map);
            List<Integer> list = new ArrayList<>();
            for(Integer key : map.keySet()){
                if(map.get(key) == max) list.add(key);
            }
            
            int[] res = new int[list.size()];
            for(int i = 0; i < res.length; i++){
                res[i] = list.get(i);
            }
            return res;
            
        }
        
        public int helper(TreeNode root, Map<Integer, Integer> map){
            if(root == null) return 0;
            int sum = root.val + helper(root.left, map) + helper(root.right, map);
            int count = map.getOrDefault(sum, 0) + 1;
            map.put(sum, count);
            max = Math.max(count, max);
            return sum;
        }
    }
    

Log in to reply
 

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