1 递归—中序遍历
【极端情况】:BST树中所有节点唯一,则所有节点均是众数
代码语言:javascript复制/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<int> vec;
TreeNode* pre = nullptr;
int cont = 0, maxCont = 0;
public:
void traverse(TreeNode* cur) {
if (!cur) return;
traverse(cur->left);
/**以下是中间节点操作**/
if (pre && pre->val == cur->val) cont ;
else cont = 0;
// 极端情况: 所有元素均唯一,则所有元素都是众数
if (cont == maxCont) vec.emplace_back(cur->val);
if (cont > maxCont) {
maxCont = cont;
// 间接清空之前vector
vec = vector<int> {cur->val};
}
pre = cur;
/**以上是中间节点操作**/
traverse(cur->right);
}
vector<int> findMode(TreeNode* root) {
traverse(root);
return vec;
}
};