题目详情
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
- 结点左子树中所含结点的值小于等于当前结点的值
- 结点右子树中所含结点的值大于等于当前结点的值
- 左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],
1
\
2
/
2
返回[2].
提示:如果众数超过1个,不需考虑输出顺序
进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
——题目难度:简单
-下面代码(带注释)
/**
* 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> ans; //最后的结果数组
/*中序遍历*/
void inOrder(TreeNode *root, TreeNode *&pre, int &cur_count, int &max_count, int &ans_size) {
if (root == NULL) return ;
inOrder(root->left, pre, cur_count, max_count, ans_size); //先左
if (pre && root->val == pre->val) {
cur_count++;
} else {
cur_count = 1;
}
if (cur_count > max_count) {
max_count = cur_count;
ans_size = 1;
}
else if (cur_count == max_count) {
if (!ans.empty()) { //第一次中序遍历不会进入这里面
ans[ans_size] = root->val;
}
ans_size++;
}
pre = root;
inOrder(root->right, pre, cur_count, max_count, ans_size); //后右
}
public:
vector<int> findMode(TreeNode* root) {
int max_count = 0; //众数的出现次数
int cur_count = 0; //当前元素的出现次数
int ans_size = 0; //结果数组的长度
TreeNode *pre = NULL; //pre指向上一次的元素
inOrder(root, pre, cur_count, max_count, ans_size); //第一次中序遍历
ans.resize(ans_size);
ans_size = 0;
pre = NULL;
cur_count = 0;
inOrder(root, pre, cur_count, max_count, ans_size); //第二次中序遍历
return ans;
}
};
结果