Leetcode 501 Solution
This article provides solution to leetcode question 501 (find-mode-in-binary-search-tree)
Access this page by simply typing in "lcs 501" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/find-mode-in-binary-search-tree
Solution
/**
* 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 {
vector<int> res;
int curr_cnt = 0;
int max_cnt = 0;
public:
void findMode(TreeNode* root, int& prev) {
if (root == NULL)
return;
findMode(root->left, prev);
if (max_cnt != 0 && prev == root->val)
curr_cnt++;
else
{
prev = root->val;
curr_cnt = 1;
}
if (curr_cnt > max_cnt)
{
max_cnt = curr_cnt;
res.clear();
res.push_back(root->val);
}
else if (curr_cnt == max_cnt)
res.push_back(root->val);
findMode(root->right, prev);
}
vector<int> findMode(TreeNode* root) {
int prev = INT_MAX;
findMode(root, prev);
return res;
}
};