题目链接:
https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/
知识
树的中序遍历
如下图:
如右图所示二叉树,中序遍历结果:DBEAFC
(来自百度百科)
算法
Morris中序遍历。
分析
由于该BST树有如下特性:
1、结点左子树中所含结点的值小于等于当前结点的值。
2、结点右子树中所含结点的值大于等于当前结点的值。
3、左子树和右子树都是二叉搜索树。
则保证了中序遍历之后,会形成相同数据扎堆的情况。
便于统计众数。
代码
/**
* 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 {
public:
//中序遍历一定可以实现扎堆现象
int base, count, maxCount;
vector<int> answer;
void update(int x) {
if (x == base) {
++count;
} else {
count = 1;
base = x;
}
if (count == maxCount) {
answer.push_back(base);
}
if (count > maxCount) {
maxCount = count;
answer = vector<int> {
base};
}
}
vector<int> findMode(TreeNode* root) {
TreeNode *cur = root, *pre = nullptr;
while (cur) {
//Morris中序遍历
if (!cur->left) {
update(cur->val);
cur = cur->right;
continue;
}
pre = cur->left;
while (pre->right && pre->right != cur) {
pre = pre->right;
}
if (!pre->right) {
pre->right = cur;
cur = cur->left;
} else {
pre->right = nullptr;
update(cur->val);
cur = cur->right;
}
}
return answer;
}
};