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
Find Mode in Binary Search Tree INPUT Binary Search Tree: 1 2 2 Array representation: [1, null, 2, 2] ALGORITHM STEPS (Optimized In-Order DFS) 1 In-Order Traversal Visit nodes: left-root-right 2 Track Current Count Compare with prev value 3 Update Max Count Reset modes if new max 4 Collect Modes Add when count == maxCount In-Order Visit Sequence: 1 cnt:1 --> 2 cnt:1 --> 2 cnt:2 maxCount = 2, mode = [2] FINAL RESULT Mode Found: 2 Frequency: 2 times Output Array: [2] OK - Mode Found! Value 1: count 1 Value 2: count 2 (max) Key Insight: In-order traversal of a BST visits nodes in sorted order. This means duplicate values appear consecutively, allowing us to count frequencies in O(1) space by comparing each node with the previous one. This eliminates the need for a hash map! TutorialsPoint - Find Mode in Binary Search Tree | Optimized In-Order DFS Approach
Asked in
Google 15 Amazon 12 Microsoft 8
64.8K Views
Medium Frequency
~15 min Avg. Time
2.4K 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