Sunday, October 1, 2017

508. Most Frequent Subtree Sum

https://leetcode.com/problems/most-frequent-subtree-sum/description/
    int postOrder(TreeNode* node, unordered_map<int,int>& mp) {
        if(!node) return 0;
        int l = postOrder(node->left, mp);
        int r = postOrder(node->right, mp);
        int s = l+r+node->val;
        mp[s]++;
        return s;
    }
    vector<int> findFrequentTreeSum(TreeNode* root) {
        if(!root) return {};
        unordered_map<int,int> mp;
        postOrder(root, mp);
        map<int,vector<int>> cnt2node;
        for(auto &m : mp) {
            cnt2node[m.second].push_back(m.first);
        }
        return (*cnt2node.rbegin()).second;
    }

No comments:

Post a Comment