问题
思路
常规题。遍历一遍,找出出现次数最大的值。
然后枚举哈希表即可。
代码
/**
* 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> findMode(TreeNode* root) {
std::vector<int> ret;
if(!root)
return ret;
std::map<int, int> mapper;
int max = 0;
preOrder(root,mapper,max);
typedef std::map<int, int>::const_iterator const_iter;
const_iter b = mapper.begin();
const_iter e = mapper.end();
while(b != e){
if(b->second==max)
ret.push_back(b->first);
++b;
}
return ret;
}
private:
void preOrder(TreeNode* root, std::map<int,int>& mapper, int& max){
if(!root)
return ;
int cnt = ++mapper[root->val];
max = std::max(max, cnt);
preOrder(root->left, mapper, max);
preOrder(root->right, mapper, max);
}
};