Java DFS straight forward solution, 13 ms


  • 0
    C
    public class Solution {
        
        Map<Integer, Integer> map = new HashMap<>();
        int max = 0;
        List<Integer> sums = new ArrayList<>();
        public int[] findFrequentTreeSum(TreeNode root) {
            subSum(root);
            int[] res = new int[sums.size()];
            for(int i = 0; i < sums.size(); i++) res[i] = sums.get(i);
            return res;
        }
        
        private int subSum(TreeNode node) {
            if(node == null) return 0;
            int sum = node.val;
            if(node.left != null) sum += subSum(node.left);
            if(node.right != null) sum += subSum(node.right);
            int f = map.getOrDefault(sum, 0) + 1;
            map.put(sum, f);
            if(f > max) {
                max = f;
                sums = new ArrayList<>();
                sums.add(sum);
            }else if(f == max) sums.add(sum);
            return sum;
        }
    }
    

Log in to reply
 

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