My AC solution use map 18ms


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

Log in to reply
 

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