题目链接: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) {}
* };
*/
class Solution {
public:
vector<int> findMode(TreeNode* root) {
dfs(root);
return res;
}
void dfs(TreeNode* root){
if(!root) return ;
dfs(root->left);
//只计数+数值
if(!pre){//说明是当前第一个节点
count++;
pre=root;
}else if(pre->val==root->val){//和前面一个数值一样
count++;
}else{//和前面一个数值不一样
pre=root;
count=1;
}
//考虑是否更新
if(count>maxCount){
res.clear();
maxCount=count;
res.push_back(pre->val);
}else if(count==maxCount){
res.push_back(pre->val);
}
dfs(root->right);
}
private:
vector<int> res;
int maxCount=0;
int count=0;
TreeNode* pre=nullptr;//用于存储上一个的指针,同时也保存了上一个指针的数值
};