給定一個有相同值的二叉搜尋樹(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() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int base = 0;
int cnt = 0;
int maxcnt = 0;
vector<int>ans;
vector<int> findMode(TreeNode* root) {
dfs(root);
return ans;
}
void compare_node(int x)
{
if (x==base)
{
cnt++;
}else
{
base = x;
cnt = 1;
}
if (cnt == maxcnt) ans.push_back(base);
if (cnt > maxcnt)
{
maxcnt = cnt;
ans = vector<int>{base};
}
}
void dfs(TreeNode *root)
{
if (root==nullptr) return ;
dfs(root->left);
compare_node(root->val);
dfs(root->right);
}
};