[LeetCode] 508. Most Frequent Subtree Sum

 发布日期:2018-11-14 13:27:41  阅读次数:阅读数:398  来源:

Most Frequent Subtree Sum

Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.
在这里插入图片描述

解析

给定一个二叉树,求出现频率最高的子树之和。

解法:postorder

建立一个哈希表,保存子树和以及出现的频率。利用后序遍历,每次记录对当前节点的子树和,并更新频率最大。

class Solution {
public:
    vector<int> findFrequentTreeSum(TreeNode* root) {
        if(!root) return {};
        vector<int> res;
        unordered_map<int,int> m;
        int mx = 0;
        int b = postorder(root, m, mx);
        for(auto a : m){
            if(a.second == mx){
                res.push_back(a.first);
            }
        }
        return res;
    }
    
    int postorder(TreeNode* root, unordered_map<int, int>& m, int& mx) {
        if(!root) return 0;
        int left = postorder(root->left,m,mx);
        int right = postorder(root->right,m,mx);
        m[right+left+root->val] ++;
        mx = max(mx, m[right+left+root->val]);
        return right+left+root->val; 
    }
};
如果您有好的新闻与建议,欢迎点击文章投稿

    发表评论

    电子邮件地址不会被公开。

  • 内容

  • 网名