501. 二叉搜索树中的众数 - 力扣(LeetCode) (leetcode-cn.com)
二叉搜索树中的众数
递归
- 该非严格意义上的二叉搜索树的**中序遍历结果是不严格递增**的
- 保存上次访问指针
class Solution {
public:
int maxCount;
int count;
TreeNode* pre;
vector<int> ans;
void searchBST(TreeNode* cur) {
if (!cur) return;
// 左
searchBST(cur->left);
// 中
// 如果是第一个结点,没有前驱,频率为1
if (!pre) count = 1;
// 如果当前结点值等于前驱结点 频率++
else if (pre->val == cur->val) count++;
// 否则刷新频率
else count = 1;
// 记录前驱结点
pre = cur;
// 判断是否刷新最大频率
if (count == maxCount) ans.emplace_back(cur->val);
else if (count > maxCount) {
maxCount = count;
ans.clear();
ans.emplace_back(cur->val);
}
// 右
searchBST(cur->right);
return;
}
vector<int> findMode(TreeNode* root) {
searchBST(root);
return ans;
}
};
非递归
- 该非严格意义上的二叉搜索树的**中序遍历结果是不严格递增**的
- 保存上次访问指针
class Solution {
public:
vector<int> findMode(TreeNode* root) {
vector<int> ans;
// 保存前驱结点
TreeNode* pre = nullptr;
// 频率
int count = 0;
int maxCount = 0;
stack<TreeNode*> stk;
if (root) stk.push(root);
while (!stk.empty()) {
TreeNode* node = stk.top();
stk.pop();
if (node) {
if (node->right) stk.push(node->right);
stk.push(node);
stk.push(nullptr);
if (node->left) stk.push(node->left);
}
// 仅需要处理结点, 处理方式同递归方法一致
else {
node = stk.top();
stk.pop();
if (!pre) count = 1;
else if (pre->val == node->val) count++;
else count = 1;
pre = node;
if(count == maxCount) ans.emplace_back(node->val);
else if (count > maxCount) {
maxCount = count;
ans.clear();
ans.emplace_back(node->val);
}
}
}
return ans;
}
};