508 Most Frequent Subtree Sum 出现频率最高的子树和

详见:https://leetcode.com/problems/most-frequent-subtree-sum/description/

C++:

/**
 * 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:
    vector<int> findFrequentTreeSum(TreeNode* root) {
        vector<int> res;
        int cnt=0;
        unordered_map<int,int> m;
        postorder(root,m,cnt,res);
        return res;
    }
    int postorder(TreeNode* node,unordered_map<int,int> &m,int &cnt,vector<int> &res)
    {
        if(!node)
        {
            return 0;
        }
        int left=postorder(node->left,m,cnt,res);
        int right=postorder(node->right,m,cnt,res);
        int sum=left+right+node->val;
        ++m[sum];
        if(m[sum]>=cnt)
        {
            if(m[sum]>cnt)
            {
                res.clear();
            }
            res.push_back(sum);;
            cnt=m[sum];
        }
        return sum;
    }
};

 参考:http://www.cnblogs.com/grandyang/p/6481682.html

posted on 2018-04-22 15:45  lina2014  阅读(119)  评论(0编辑  收藏  举报

导航