Find Mode in Binary Search Tree
Trees
EasyLeetCode #501
Problem Statement
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.
Example
Input: root = [1,null,2,2]
Output: [2]
Algorithm Explanation
A straightforward approach is to traverse the tree and use a hash map to store the frequency of each node's value. Then, we can find the maximum frequency and return all values with that frequency.
Algorithm Steps
- In-order Traversal: We can perform an in-order traversal of the BST. This will give us the node values in sorted order.
- Track Current Streak: As we traverse, we can keep track of the current value, its frequency (streak), and the maximum frequency seen so far.
- Update Mode(s): If the current streak exceeds the maximum frequency, we clear our result list and add the current value. If the streak equals the maximum frequency, we just add the current value to the list.
Start
Starting in-order traversal.
Prev: null
Current Count: 0
Max Count: 0
Modes: []
Find Mode in BST Solution