Find Mode in Binary Search Tree - Problem
Given the root of a binary search tree (BST) with duplicates, find all the mode(s) - the values that appear most frequently in the tree.
A mode is a value that appears with the highest frequency. If multiple values share the same highest frequency, return all of them in any order.
BST Properties:
- Left subtree contains nodes with keys โค current node's key
- Right subtree contains nodes with keys โฅ current node's key
- Both subtrees are also BSTs
For example, in BST [1,null,2,2], the value 2 appears twice while 1 appears once, so [2] is returned as it has the highest frequency.
Input & Output
example_1.py โ Basic BST with duplicate values
$
Input:
root = [1,null,2,2]
โบ
Output:
[2]
๐ก Note:
The value 2 appears twice while 1 appears only once, making 2 the mode with frequency 2.
example_2.py โ Multiple modes case
$
Input:
root = [1,1,2,2,3,3]
โบ
Output:
[1,2,3]
๐ก Note:
All values 1, 2, and 3 appear exactly twice, so they all share the highest frequency and are all modes.
example_3.py โ Single node edge case
$
Input:
root = [5]
โบ
Output:
[5]
๐ก Note:
Tree has only one node with value 5, so 5 is the only mode with frequency 1.
Visualization
Tap to expand
Understanding the Visualization
1
Ordered Traversal
Walk through the BST library in order - this naturally groups identical books together
2
Count Consecutive
As you encounter identical books, count them efficiently since they appear consecutively
3
Track Popularity
Keep track of the highest popularity (frequency) found so far
4
Identify Champions
Collect all books that achieve the maximum popularity level
Key Takeaway
๐ฏ Key Insight: BST's in-order traversal gives us values in sorted order, allowing efficient consecutive counting in a single pass - no hash table needed!
Time & Space Complexity
Time Complexity
O(n)
Single in-order traversal visiting each node exactly once
โ Linear Growth
Space Complexity
O(h)
Recursion stack depth equals tree height h, plus result array
โ Linear Space
Constraints
- The number of nodes in the tree is in the range [1, 104]
- -105 โค Node.val โค 105
- The tree is guaranteed to be a valid BST
- Follow-up: Could you do that without using any extra space? (Assume the implicit stack space of the recursion doesn't count)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code