题目描述:
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]
.
Note: If a tree has more than one mode, you can return them in any order.
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
找出BST的众数,要求不使用额外空间。自然是利用递归进行遍历,由于是BST,所以在中序遍历序列中,相等元素是在一起的,所以我们可以用三个变量存储上一次遍历的数值、上一次数值的出现次数和当前众数的出现次数,那么根据当前元素和上一次元素的比较,我们更新这三个变量,得到最终的众数。
class Solution {
public:
vector<int> findMode(TreeNode* root) {
vector<int> result;
if(root==NULL) return result;
int pre=INT_MIN;
int count=0;
int max_count=0;
inorder(root,pre,count,max_count,result);
return result;
}
void inorder(TreeNode* root, int& pre, int& count, int& max_count, vector<int>& result)
{
if(root==NULL) return;
inorder(root->left,pre,count,max_count,result);
if(root->val==pre) count++;
else
{
pre=root->val;
count=1;
}
if(count==max_count) result.push_back(root->val);
else if(count>max_count)
{
result.clear();
result.push_back(root->val);
max_count=count;
}
inorder(root->right,pre,count,max_count,result);
}
};