计算二叉搜索树的众数
C++ 代码
/**
* 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) {}
* };
*/
class Solution {
public:
// BST 的中序遍历是有序的,中序遍历的时候当做数组来统计即可
vector<int> findMode(TreeNode* root) {
dfs(root);
return res_;
}
void dfs(TreeNode* root) {
if(!root) return;
dfs(root->left);
// handle root->val
// 修改当前的计数器 now_cnt_ 和 当前的值 last_
int val = root->val;
if(val == last_) {
now_cnt_++;
} else {
last_ = val;
// reset
now_cnt_ = 1;
}
// 判断是否有众数修改
if(now_cnt_ > max_cnt_) {
res_ = {last_};
max_cnt_ = now_cnt_;
}else if(now_cnt_ == max_cnt_) res_.push_back(last_);
dfs(root->right);
}
private:
vector<int> res_;
int last_ = INT_MIN;
int max_cnt_ = 0;
int now_cnt_ = 0;
};