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