Find Mode in Binary Search Tree
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than or equal to the node's key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
- Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2]
,
1
\
2
/
2
return [2]
.
在一颗二叉搜索树中,中序遍历能够获得一个有序的递增序列,根据题意我们需要找到一个或者一些出现次数最多的元素,可以通过中序遍历来记录每个不同元素出现次数并找到出现次数最多的元素记录下来即可。中序遍历先遍历左子树,根,最后再遍历右子树。
max_count:最大次数(依靠temp_count不断更新)
temp_count:当前记录的元素所出现的次数
temp_val:当前记录的元素
/**
* 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:
vector<int> findMode(TreeNode* root)
{
find(root);
return res;
}
int max_count=0;
int temp_count=0;
int temp_val=INT_MIN;
vector<int> res;
void find(TreeNode* root)
{
if(root==NULL) return ;
//中序遍历 递增序列
find(root->left); //左子树
if(root->val!=temp_val) //记录第一次被发现的元素
temp_count=1;
else
temp_count++; //记录被发现的相同元素
if(temp_count>max_count)//更新max_count
{
max_count=temp_count;
res.clear(); //更新res中存放的最大元素
res.push_back(root->val);
}
else if(temp_count==max_count)//出现多个相同最大次数的元素
{
res.push_back(root->val);
}
temp_val=root->val;
find(root->right); //右子树
}
};