二叉搜索树的元素使用中序遍历,则可以得到一个有序的序列,那么判断前一个节点 和 当前节点的值是否相等,就可以统计一个数出现的次数,当一个数出现的次数大于当前的最大次数时,更新众数并清空之前的返回数组,添加新的众数进入数组。
这样就只需遍历一次,且无需使用map等容器耗费额外的空间。
/**
* 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:
void searchBST(TreeNode* root){
if(root == nullptr){
return;
}
searchBST(root->left);
if(pre == nullptr){
count = 1;
}else if(pre->val == root->val){
count++;
}else{
count = 1;
}
pre = root;
if(count == maxCount){
result.push_back(root->val);
}else if(count > maxCount){
maxCount = count;
result.clear();
result.push_back(root->val);
}
searchBST(root->right);
}
vector<int> findMode(TreeNode* root) {
searchBST(root);
return result;
}
private:
int count = 0;
int maxCount = 0;
TreeNode * pre = nullptr;
vector<int> result;
};