[LeetCode] 508. Most Frequent Subtree Sum

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; 
    }
};

猜你喜欢

转载自blog.csdn.net/Peng_maple/article/details/83870077