Find Mode in Binary Search Tree
Problem
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.
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
Constraints
- The number of nodes in the tree is in the range
[1, 104]
. -105 <= Node.val <= 105
Solution
The problem Find Mode in Binary Search Tree
can be solved using an inorder traversal. When a binary search tree is traversed inorder, its elements are sorted in ascending order. Therefore, modes can be found by simply counting the number of appearances for elements in a sorted list.
Implementation
/**
* 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
{
private:
int max_count;
int prev_val;
int count;
public:
void updateMode(vector<int> &modes)
{
if (max_count < count)
{
modes.clear();
max_count = count;
}
if (max_count == count)
modes.push_back(prev_val);
}
void helper(TreeNode *root, vector<int> &modes)
{
if (root == NULL)
return;
helper(root->left, modes);
if (root->val == prev_val)
count += 1;
else
{
updateMode(modes);
prev_val = root->val;
count = 1;
}
helper(root->right, modes);
}
vector<int> findMode(TreeNode *root)
{
prev_val = root->val;
max_count = count = 0;
vector<int> ret;
helper(root, ret);
updateMode(ret);
return ret;
}
};