-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_mode_in_binary_search_tree.cpp
More file actions
83 lines (74 loc) · 1.77 KB
/
find_mode_in_binary_search_tree.cpp
File metadata and controls
83 lines (74 loc) · 1.77 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
* =====================================================================================
*
* Filename: find_mode_in_binary_search_tree.cpp
*
* Description: Find Mode in Binary Search Tree.
*
* Version: 1.0
* Created: 02/28/19 06:24:41
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <vector>
#include <unordered_map>
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
std::vector<int> findMode(TreeNode* root)
{
std::unordered_map<int, int> counts;
dfsTree(root, counts);
std::vector<int> modes;
int max = 0;
for (const auto& item: counts)
{
if (item.second < max)
{
continue;
}
// item.second >= max
if (item.second > max)
{
modes.clear();
max = item.second;
}
modes.push_back(item.first);
}
return modes;
}
private:
void dfsTree(TreeNode* node, std::unordered_map<int, int>& counts)
{
if (node == NULL)
{
return;
}
auto ret_pair = counts.insert(std::make_pair(node->val, 1));
if (!ret_pair.second)
{
ret_pair.first->second += 1;
}
dfsTree(node->left, counts);
dfsTree(node->right, counts);
}
};
int main(int argc, char* argv[])
{
TreeNode* root = NULL;
auto modes = Solution().findMode(root);
return 0;
}