Easy Java Solution With HashMap


  • 0
    H
        public int[] findFrequentTreeSum(TreeNode root) {
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            traverse(root, map);
            List<Integer> list = new ArrayList<Integer>();
            int max = 0;
            for (int i : map.keySet()) {
                if (map.get(i) > max) {
                    max = map.get(i);
                    list.clear();
                    list.add(i);
                } else if (map.get(i) == max) {
                    list.add(i);
                } 
            }
            int[] result = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                result[i] = list.get(i);
            }
            return result;
        }
        
        private int traverse(TreeNode node, Map<Integer, Integer> map) {
            if (node == null) {
                return 0;
            }
            int leftSum = traverse(node.left, map);
            int rightSum = traverse(node.right, map);
            int sum = leftSum + rightSum + node.val;
            map.put(sum, map.getOrDefault(sum, 0) + 1);
            return sum;
        }
    

Log in to reply
 

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