您的位置:首页 > 其它

leetcode-501-Find Mode in Binary Search Tree

2017-02-15 22:34 344 查看

问题

题目:[leetcode-501]

思路

常规题。遍历一遍,找出出现次数最大的值。

然后枚举哈希表即可。

代码

/**
* 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);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: