/**
* 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;
}
vector<int> res;
int cnt = 0;
int pre = -1;
int maxCnt = 0;
void dfs(TreeNode* root) {
if (root == nullptr) {
return;
}
dfs(root->left);
if (root->val == pre) {
cnt++;
} else {
cnt = 1;
pre = root->val;
}
if (cnt == maxCnt) {
res.push_back(root->val);
}
if (cnt > maxCnt) {
maxCnt = cnt;
res = vector<int> {root->val};
}
dfs(root->right);
}
};