题目描述,链接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。
本文介绍了一种使用递归遍历与哈希映射的方法来找出二叉搜索树中出现频率最高的元素。通过记录每个节点值出现的次数,并追踪最大出现次数,最终返回出现最频繁的一个或多个元素。
438

被折叠的 条评论
为什么被折叠?



