Very Short and Crisp Java Solution


  • 0
    V

    Start from leaf nodes and traverse until root of the tree tracking sum at every level. Keep a mapping between sum and number of nodes with that sum.

    public class Solution {
        int max = Integer.MIN_VALUE;
        public int[] findFrequentTreeSum(TreeNode root) {
            Map<Integer, Integer> map = new HashMap<>();
            h(root, map);
            return map.entrySet().stream().filter(entry-> entry.getValue() == max).mapToInt(entry->entry.getKey()).toArray();
        }
        
        private int h(TreeNode root, Map<Integer, Integer> map) {
            if (root == null) return 0;
            int sum = root.val +  h(root.left, map) + h(root.right, map);
            map.put(sum, map.getOrDefault(sum,0)+1);
            max = Math.max(max, map.get(sum));
            return sum;
        }
    }
    

Log in to reply
 

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