首页 > 其他 > 详细

LeetCode "501. Find Mode in Binary Search Tree"

时间:2017-01-31 10:34:15      阅读:766      评论:0      收藏:0      [点我收藏+]

It is a matter of hashmap use. For the follow-up:

typedef unordered_map<int, unsigned> HM;
class Solution {
    HM go(TreeNode *p)
    {
        if(!p) return HM();
        
        auto rl = go(p->left);
        auto rr = go(p->right);
        
        HM r = rl;
        for(auto &kv : rr) r[kv.first] += kv.second;
        r[p->val] ++;
        
        return r;
    }
public:
    vector<int> findMode(TreeNode* root) 
    {
        auto h = go(root);

        int mcnt = 0;
        vector<int> ret;
    
        for(auto &kv : h)
        {
            if(kv.second > mcnt)
            {
                mcnt = kv.second;
                ret = {kv.first};
            }
            else if(kv.second == mcnt)
            {
                ret.push_back(kv.first);
            }
        }
    
        return ret;
    }
};

LeetCode "501. Find Mode in Binary Search Tree"

原文:http://www.cnblogs.com/tonix/p/6358629.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!