Easy Java solution


  • 0
    public class Solution {
        Map<TreeNode, Integer> sumMap = new HashMap(); // node:sum
        Map<Integer, Integer> freqMap = new HashMap(); // sum:freq
        int max = 0;
        public int[] findFrequentTreeSum(TreeNode root) {
            if (root == null) return new int[0];
            calSum(root);
            List<Integer> res = new ArrayList();
            for (int key : freqMap.keySet()) {
                if (freqMap.get(key) == max) {
                    res.add(key);
                }
            }
            return res.stream().mapToInt(i->i).toArray();
        }
        
        private int calSum(TreeNode root) {
            if (root == null) return 0;
            int s = calSum(root.left) + calSum(root.right) + root.val;
            sumMap.put(root, s);
            freqMap.put(sumMap.get(root), freqMap.getOrDefault(sumMap.get(root), 0) + 1);
            if (freqMap.get(sumMap.get(root)) > max) max = freqMap.get(sumMap.get(root));
            return s;
        }
    }
    

Log in to reply
 

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