Keshawn_lu's Blog

Leetcode 501. 二叉搜索树中的众数

字数统计: 317阅读时长: 1 min
2020/09/24 Share

题目简介:

给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。

假定 BST 有如下定义:

  • 结点左子树中所含结点的值小于等于当前结点的值
  • 结点右子树中所含结点的值大于等于当前结点的值
  • 左子树和右子树都是二叉搜索树

例如:
给定 BST [1,null,2,2],

1
2
3
4
5
1
\
2
/
2

返回[2].

提示:如果众数超过1个,不需考虑输出顺序

思路:

没想太多,首先第一次遍历,将记录存入哈希表中,并找出其中的最大出现次数Maxnum

第二次遍历哈希表,将出现次数等于Maxnum的值存入结果数组中,最后返回即可。

tip:

  • 学会哈希表的遍历

代码如下:

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
/**
* 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:

unordered_map<int, int> map;
vector<int> res;

int Maxnum = INT_MIN;

void dfs(TreeNode* root){

if(!root)
return;

dfs(root -> left);

map[root -> val]++;
Maxnum = max(Maxnum, map[root -> val]);

dfs(root -> right);
}

vector<int> findMode(TreeNode* root) {

dfs(root);

for(auto i : map){

if(i.second == Maxnum)
res.push_back(i.first);
}

return res;

}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: