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
BST Mode Finding - Library Analogy๐Ÿ“š Ordered Library (BST Structure)Book1Count: 4Book1Count: 4Book1Count: 4Book1Count: 4Book3Count: 2Book3Count: 2๐Ÿ‘ฉโ€๐ŸซLibrarian(In-order walk)๐Ÿ” Counting ProcessWalking in order: 1โ†’1โ†’1โ†’1โ†’3โ†’3Current max frequency: 4๐Ÿ† Most PopularBook 1 (4 copies)
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

n
2n
โœ“ Linear Growth
Space Complexity
O(h)

Recursion stack depth equals tree height h, plus result array

n
2n
โœ“ 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)
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
89.4K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen