写的比较丑陋…
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//DFS&HASH 有额外空间开销
//中序遍历 , 树变顺序表 , 摩尔斯投票
class Solution {
public:
int maxCount = -1;
void helper(TreeNode * root, int &base, int & count, vector<int> & ans) {
if (root == NULL) {
return;
}
helper(root->left, base, count, ans);
if (maxCount == -1) {
count = 1;
base = root->val;
maxCount = 0;
}
else if (root->val == base) {
count++;
}
else {
if (count == maxCount) {
ans.push_back(base);
base = root->val;
count = 1;
}
else if (count > maxCount) {
maxCount = count;
ans.clear();
ans.push_back(base);
base = root->val;
count = 1;
}
else {
base = root->val;
count = 1;
}
}
helper(root->right, base, count, ans);
}
vector<int> findMode(TreeNode* root) {
int base = 0;
int count = 0;
vector<int> ans;
if(root == NULL){
return ans;
}
helper(root, base, count, ans);
if (count == maxCount) {
ans.push_back(base);
}
else if (count > maxCount) {
maxCount = count;
ans.clear();
ans.push_back(base);
}
return ans;
}
};