Leetcode 501. Find Mode in Binary Search Tree
Given the root of a binary search tree (BST), return the mode(s) (i.e., the most frequently occurred element) in it.
[1, 10^4]
.-10^5 <= Node.val <= 10^5
.unordered_map<int, int>
) to count occurrences of each value.#include <unordered_map>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
vector<int> findMode(TreeNode* root) {
if (!root) return {};
unordered_map<int, int> countMap;
inorderTraversal(root, countMap);
int maxCount = 0;
for (const auto& pair : countMap) {
if (pair.second > maxCount) {
maxCount = pair.second;
}
}
vector<int> modes;
for (const auto& pair : countMap) {
if (pair.second == maxCount) {
modes.push_back(pair.first);
}
}
return modes;
}
private:
void inorderTraversal(TreeNode* node, unordered_map<int, int>& countMap) {
if (!node) return;
inorderTraversal(node->left, countMap);
countMap[node->val]++;
inorderTraversal(node->right, countMap);
}
};
n
is the number of nodes in the tree. Each node is visited once.n
to find the maximum frequency and collect modes.Overall Time Complexity: O(n)
h
is the height of the tree (worst case O(n) for a skewed tree).Overall Space Complexity: O(n) in the worst case due to the hashmap storing counts of all nodes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?