[leetcode]508. Most Frequent Subtree Sum二叉树中出现最多的值

遍历二叉树,用map记录sum出现的次数,每一个新的节点都统计一次。

遍历完就统计map中出现最多的sum

Map<Integer,Integer> map = new HashMap<>();
    public int[] findFrequentTreeSum(TreeNode root) {
        helper(root);
        int max = 0;
        List<Integer> list  = new ArrayList<>();
        for (int key : map.keySet()) {
            int v = map.get(key);
            if (v>max)
            {
                list.clear();
                list.add(key);
                max = v;
            }
            else if (v==max) list.add(key);
        }
        int[] res = new int[list.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = list.get(i);
        }
        return res;
    }
    public int helper(TreeNode root)
    {
        if (root==null) return 0;
        int cur = root.val;
        cur+= helper(root.left);
        cur+=helper(root.right);
        map.put(cur,map.getOrDefault(cur,0)+1);
        return cur;
    }
原文地址:https://www.cnblogs.com/stAr-1/p/8390478.html