Easy Understand Java AC solution


  • 0
    M
    1. Use map to store the sum and its frequency, key: sum, value: the frequency of this sum
    2. Traverse the map to get the most frequency sum
    public class Solution {
        public int[] findFrequentTreeSum(TreeNode root) {
            Map<Integer, Integer> map = new HashMap<>();
            getSum(root, map);
            int maxFreq = 0, counter = 0;
            for (int key : map.keySet()) {
                if (map.get(key) > maxFreq) {
                    maxFreq = map.get(key);
                    counter = 1;
                } else if (map.get(key) == maxFreq) {
                    counter++;
                }
            }
            int[] res = new int[counter];
            int index = 0;
            for (int key : map.keySet()) {
                if (map.get(key) == maxFreq) {
                    res[index++] = key;
                }
            }
            return res;
        }
        public int getSum(TreeNode root, Map<Integer, Integer> map) {
            if (root == null) return 0;
            int sum = root.val + getSum(root.left, map) + getSum(root.right, map);
            map.put(sum, map.getOrDefault(sum, 0) + 1);
            return sum;
        }
    }
    

Log in to reply
 

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