[LeetCode] Find Mode in Binary Search Tree

501. Find Mode in Binary Search Tree

Given the root of a binary search tree (BST) with duplicates, return all the mode(s)) (i.e., the most frequently occurred element) in it.

If the tree has more than one mode, return them in any order.

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.
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
/**
* 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 {
void dfs(TreeNode* t, unordered_map<int,int>& f) {
if(!t) return;
f[t->val] += 1;
dfs(t->left,f);
dfs(t->right,f);
}
public:
vector<int> findMode(TreeNode* root) {
unordered_map<int, int> freq;
dfs(root,freq);
vector<int> res;
int ma = -1;
for(auto& [_,v] : freq) ma = max(ma, v);
for(auto& [k,v] : freq) if(v == ma) res.push_back(k);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/11/01/PS/LeetCode/find-mode-in-binary-search-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.