Java code


  • 0
    B
    public class Solution {
        
        public int[] findFrequentTreeSum(TreeNode root) {
            if (root == null) {
                return new int[0];
            }
            
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            helper(root, map);
            
            int max = 0;
            int count = 0;
            for (int val : map.values()) {
                if (val > max) {
                    max = val;
                    count = 1;
                } else if (val == max) {
                    count++;
                }
            }
            int[] res = new int[count];
            int index = 0;
            for (int key : map.keySet()) {
                if (map.get(key) == max) {
                    res[index++] = key;
                }
            }
            
            return res;
        }
        
        public int helper(TreeNode root, HashMap<Integer, Integer> map) {
            if (root == null) {
                return 0;
            }
            
            int left = helper(root.left, map);
            int right = helper(root.right, map);
            int sum = left + right + root.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.