题目描述,链接https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/
解题代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include<algorithm>
class Solution {
public:
vector<int> findMode(TreeNode* root) {
vector<int> ans;
if(root==NULL){
return ans;
}
map<int, int> counter;
counter[root->val]++;//记录每个数字出现的次数
traversal(counter, root);
int max = -1;//记录出现次数的最大值
for(auto i=counter.begin(); i != counter.end(); i++){
if(i->second == max){
ans.push_back(i->first);
}else if(i->second > max){
max = i->second;
ans.clear();
ans.push_back(i->first);
}
}
return ans;
}
void traversal(map<int, int>& counter, TreeNode* root){
if(root->left!=NULL){
counter[root->left->val]++;
traversal(counter, root->left);
}
if(root->right!=NULL){
counter[root->right->val]++;
traversal(counter, root->right);
}
}
};
运行结果
这里还是使用了额外的空间map。