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).
题目要求找出出现最多的元素多代表的mode,即可能有多个元素出现了相同最多次;
但是要求不能使用额外的内存资源,除了递归时栈调用所使用的资源。
可以使用二叉排序树的中序遍历方法,遍历找出出现次数最多的元素。
class Solution {
private:
vector<int> res;
int curval, maxcount = 0, tempcount = 0;
public:
void dfs_findMode(TreeNode *root){
if (root == NULL)return;
dfs_findMode(root->left);
tempcount++;
if (root->val != curval){
curval = root->val;
tempcount = 1;
}
if (tempcount > maxcount){
maxcount = tempcount;
res.clear();
res.push_back(root->val);
}
else if (tempcount == maxcount){
res.push_back(root->val);
}
dfs_findMode(root->right);
}
vector<int> findMode(TreeNode* root) {
if (root == NULL)return vector<int>{};
dfs_findMode(root);
return res;
}
};