Share my Java Solution, concise and easy to understand


  • 0
    S
    public class Solution {
        int maxCount = 0;
        int number = 0;
        public int[] findFrequentTreeSum(TreeNode root) {
            Map<Integer, Integer> map = new HashMap<>();
            helper(root, map);
            int[] res = new int[number];
            int idx = 0;
            for (Integer key : map.keySet()) {
                if (map.get(key) == maxCount) {
                    res[idx++] = key;
                }
            }
            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);
            map.put(sum, map.getOrDefault(sum, 0) + 1);
            if (map.get(sum) > maxCount) {
                maxCount = map.get(sum);
                number = 1;
            } else if (map.get(sum) == maxCount) {
                number++;
            }
            return sum;
        }
    }
    

Log in to reply
 

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