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.
Input & Output
Example 1 — Basic BST
$
Input:
root = [1,null,2,2]
›
Output:
[2]
💡 Note:
The value 2 appears twice while 1 appears once. So 2 is the mode.
Example 2 — Multiple Modes
$
Input:
root = [0]
›
Output:
[0]
💡 Note:
Single node tree, so 0 is the only and most frequent value.
Example 3 — Balanced BST
$
Input:
root = [1,0,2]
›
Output:
[0,1,2]
💡 Note:
All values appear exactly once, so all are modes.
Constraints
- The number of nodes in the tree is in the range [1, 104].
- -105 ≤ Node.val ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input BST
Binary search tree with duplicate values
2
Count Frequencies
Count occurrence of each value
3
Find Modes
Return all values with maximum frequency
Key Takeaway
🎯 Key Insight: BST in-order traversal visits values in sorted order, making duplicate counting very efficient
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code