Java Concise Solution


  • 0
    public class Solution {
        Map<Integer, Integer> map = new HashMap<>(); // sum : count
        int maxCount = 0;
        public int[] findFrequentTreeSum(TreeNode root) {
            if (root == null) return new int[0];
            dfs(root);
            List<Integer> list = new ArrayList<>();
            for (int sum : map.keySet()) {
                if (map.get(sum) == maxCount) {
                    list.add(sum);
                }
            }
            int[] res = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                res[i] = list.get(i);
            }
            return res;
        }
        private int dfs(TreeNode root) {
            if (root == null) return 0;
            int left = dfs(root.left);
            int right = dfs(root.right);
            int sum = left + right + root.val;
            map.put(sum, map.getOrDefault(sum, 0) + 1);
            maxCount = Math.max(maxCount, 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.