Problem 501 · LeetCode 501(opens in a new tab)
Find Mode in Binary Search Tree
EasyBinary search trees
A binary search tree, passed in as its root node, may hold repeated values. Here, no value in a left subtree is bigger than the node above it, and no value in a right subtree is smaller.
Return the mode or modes: the values that occur most often in the tree. If several values tie for the highest count, return all of them, in any order.
Example 1
Input: root = [2, 1, 5, 1, null, 5] Output: [1, 5] Why: 1 and 5 each appear twice, 2 only once
2 more examples and the constraints
Example 2
Input: root = [7] Output: [7] Why: the only value is the mode
Example 3
Input: root = [3, null, 4, null, 4] Output: [4] Why: 4 appears twice, 3 once
Constraints
- 1 ≤ number of nodes ≤ 10,000
- −100,000 ≤ Node.val ≤ 100,000
- Follow-up: can you do it with no extra space apart from the answer and the recursion stack?
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count with a hash mapO(n)
- In-order runsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 nodes | Verdict |
|---|---|---|---|
| Count with a hash map | O(n) | Passes; O(n) extra memory | |
| In-order runs | O(n) | Best; uses the BST order |
n = number of nodes, h = height of the tree.
Edge cases to test
- One node. [7] returns [7].
- All values distinct. Every value appears once, so every value is a mode.
- All values equal. One run covers the whole tree: a single mode.
- A tall chain. With 10,000 nodes in a line, recursion can overflow in some languages; an explicit stack is safe.
Common mistakes
- Not clearing the answer when a longer run appears, so old modes stay in it.
- Comparing with the parent instead of the previous in-order value.
- Treating the first value as a continued run because prev starts at 0 and the value is 0.
How to talk through it
- 1Clarify. Do duplicates go left, right, or both? Can several values tie? Does order matter?
- 2Give the map version. Count every value in a hash map; O(n) time and O(n) space.
- 3Use the BST. In-order reads sorted values, so equal ones are adjacent: track runs.
- 4Code the walk. Keep prev, run and best; restart the answer on a longer run, append on a tie.
- 5Test out loud. Try a single node, all distinct, all equal, and a value of 0 first.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?