Leetcode|BST属性501. BST中的众数(BST中序遍历=升序数组)
作者:互联网
1 递归—中序遍历
【极端情况】:BST树中所有节点唯一,则所有节点均是众数
/**
* 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;
}
};
标签:pre,traverse,cont,cur,val,BST,中序,升序,TreeNode 来源: https://blog.csdn.net/SL_World/article/details/114607870