Week Training: 508 Most Frequent Subtree Sum

来源:互联网 发布:java path环境变量设置 编辑:程序博客网 时间:2024/06/06 01:31

The key to this problem is using STL map. In order to store the occurrence of each sum, we have to add the sum and its occurrence to the map in every traverse, until the tree is fully gone through. Than we just traverse the map, compare every occurrence in the map with the biggest one, and decide which to push into the vector, finally return it.

class Solution {public:    vector<int> findFrequentTreeSum(TreeNode* root) {        vector<int> values;        map<int, int> count;        int HighCount = 0;        countSum(root, count, HighCount);        map<int, int> ::iterator it;        for(it=count.begin();it!=count.end();it++){            if(it->second == HighCount) values.push_back(it->first);        }        return values;    }    int countSum(TreeNode* root, map<int, int> &count, int &HighCount){        if(root==NULL)return 0;        int x = root->val;        x += countSum(root->left, count, HighCount);        x += countSum(root->right, count, HighCount);        count[x]++;        HighCount = max(HighCount, count[x]);        return x;    }};


0 0
原创粉丝点击