1. 程式人生 > >[LeetCode] 508. Most Frequent Subtree Sum

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