要求:可能有多个,不能用额外空间
思路:边中序边更新
/**
* 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> ans;
//最大次数和val,当前val和次数
int curval,curtimes,maxtimes;
void update(int val){
if(curval==val){
++curtimes;
}
else{
curval=val;
curtimes=1;
}
if(curtimes==maxtimes)ans.push_back(curval);
else if(curtimes>maxtimes){
ans={curval};
maxtimes=curtimes;
}
}
void dfs(TreeNode* root){
if(!root)return;
dfs(root->left);
update(root->val);
dfs(root->right);
}
vector<int> findMode(TreeNode* root) {
dfs(root);
return ans;
}
};