508. 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.

Examples 1
Input:

  5
 /  \
2   -3

return [2, -3, 4], since all the values happen only once, return all of them in any order.

 

Examples 2
Input:

  5
 /  \
2   -5

return [2], since 2 happens twice, however -5 only occur once.

解题思路:把每个可能的和都用hash存一下,当某个和出现的次数大于当前最大的mmax时,把之前存的数值清空,重新开始。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int getSum(TreeNode* root){
        if(!root){
            return 0;
        }
        int sum = getSum(root->left)+getSum(root->right)+root->val;
        hash[sum]++;
        if(hash[sum]>mmax){
            ans.clear();
            mmax=hash[sum];
            ans.push_back(sum);
        }
        else if(hash[sum]==mmax)
            ans.push_back(sum);
        return sum;
    }
    vector<int> findFrequentTreeSum(TreeNode* root) {
        getSum(root);
        return ans;
    }
private:
    int mmax=INT_MIN;
    vector<int>ans;
    unordered_map<int,int>hash;
};

 

posted @ 2017-04-07 11:37  Tsunami_lj  阅读(117)  评论(0编辑  收藏  举报