-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path501-find-mode-in-binary-search-tree.cpp
54 lines (45 loc) · 1.35 KB
/
501-find-mode-in-binary-search-tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* 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:
vector<int>traverse(TreeNode*root,vector<int>&ans){
if(root){
ans.push_back(root->val);
traverse(root->left,ans);
traverse(root->right,ans);
}
return ans;
}
vector<int> findMode(TreeNode* root) {
vector<int>ans;
traverse(root,ans);
unordered_map<int,int>mp;
for(int i=0;i<ans.size();i++){
mp[ans[i]]++;
}
// now we have the hashmap with the frequencies and the number ; we need to find the mode;
int mode;
int freq=0;
for(auto itr=mp.begin();itr!=mp.end();itr++){
if(freq<itr->second){
freq=itr->second;
}
}
vector<int>sol;
for(auto itr=mp.begin();itr!=mp.end();itr++){
if(itr->second==freq){
sol.push_back(itr->first);
}
}
return sol ;
}
};