Description
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],
return [2].
Note: If a tree has more than one mode, you can return them in any order.
Analysis
这道题是求BST中最经常出现的节点。
我的做法是利用DFS,利用map来记录每一个节点出现过的数目,同时用count来记录出现最多的节点的出现次数。
将count与map中的来对比,当节点出现次数等于count就将节点记录到向量中,最后得到结果。
Code
/**
* 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:
//DFS
int fun(TreeNode* root,map<int,int> &m){
if(root == NULL) return 0;
if(m.find(root->val) == m.end()){
m.insert(pair<int, int>(root->val, 1));
}
else m[root->val]++;
return max(m[root->val], max(fun(root->left, m), fun(root->right, m)));
}
vector<int> findMode(TreeNode* root) {
vector<int> res;
map<int,int> m;
int count= 0 ;
count=fun(root,m);
for(pair<int,int> ver :m){
if(ver.second == count){
res.push_back(ver.first);
}
}
return res;
}
};