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

Posted stAr_1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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;
    }

 

以上是关于[leetcode]508. Most Frequent Subtree Sum二叉树中出现最多的值的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 508. Most Frequent Subtree Sum

Leetcode508 Most Frequent Subtree Sum

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

508. Most Frequent Subtree Sum

508. Most Frequent Subtree Sum (Medium)

508. Most Frequent Subtree Sum