【53】508. Most Frequent Subtree Sum

508. Most Frequent Subtree Sum

Description Submission Solutions Add to List

  • Total Accepted: 1959
  • Total Submissions: 3846
  • Difficulty: Medium
  • Contributors: Cyber233

 

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.

 

Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.

/**
 * 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 {
    //用一个hashmap先计数每个subtree的sum出现了几次,然后再扫描这个hashmap得出最大的次数,再扫描对应的sum push进res
private:
    int calSubtreeSum(TreeNode* root, unordered_map<int, int>& cnt){//sum to cnt
        if(root == NULL) return 0;
        int sum = root -> val;
        sum += calSubtreeSum(root -> left, cnt);//dfs
        sum += calSubtreeSum(root -> right, cnt);
        cnt[sum]++;
        return sum;
    }
public:
    vector<int> findFrequentTreeSum(TreeNode* root) {
        vector<int> res;
        unordered_map<int, int> cnt;
        calSubtreeSum(root, cnt);
        int mx = INT_MIN;
        for(auto a : cnt){
            if(a.second > mx){
                mx = a.second;
            }
        }
        for(auto a : cnt){
            if(mx == a.second){
                res.push_back(a.first);
            }
        }
        return res;
    }
};

 

 

posted @ 2017-02-10 11:00  会咬人的兔子  阅读(409)  评论(0编辑  收藏  举报