15% off all plans & roadmaps Use code
See plansFind Mode in Binary Search Tree
- LeetCode 501
- Easy
- Tree Traversal Patterns (DFS & BFS)
- Recursive Inorder Traversal
Updated
TL;DR: Find the value or values that appear most often in a BST. An inorder walk visits values in sorted order, so equal values sit side by side and you can count each run in one pass.
Problem
Given the root of a binary search tree (BST) that may contain duplicates, return all of its mode values. The mode is the value that appears most often in the tree.
If more than one value has the highest count, return all of them in any order.
A BST here follows these rules:
- The left subtree of a node holds only keys less than or equal to the node's key.
- The right subtree of a node holds only keys greater than or equal to the node's key.
- Both the left and right subtrees are also binary search trees.
Example 1
Input: root = [1,null,2,2] Output: [2]
Example 2
Input: root = [0] Output: [0]
Constraints
- The number of nodes in the tree is in the range
[1, 10^4]. -10^5 <= Node.val <= 10^5
Constraints that matter
- Up to 10^4 nodes means an O(n^2) pair check is too slow, so you need one pass over the tree.
- Values lie between -10^5 and 10^5. A count array would fit, but it wastes space on a small tree and only works for this range. A map handles any key.
- The follow-up asks for O(1) extra space, so a map of counts for every distinct value is not allowed.
- A chain of 10^4 nodes is a valid BST. A recursive walk on it reaches depth 10^4, which is deeper than Python's default recursion limit.
Hints
Hint 1
The problem asks for the most frequent values, and the usual tool for counting is a hash map.
Hint 2
Visit every node once and count each value in a hash map.
Solution
Intuition
The problem asks for the most frequent values, and the usual tool for counting is a hash map. A map keeps one entry per distinct value, which costs O(n) space. The BST rule gives you a way to count without storing every value.
Picture shoppers already lined up by color, with a clerk who only remembers the last color and a tally. The prev variable is that last color, and count is the tally of identical shoppers in a row.
An inorder walk visits the left subtree, then the node, then the right subtree. On a BST that walk produces the keys in non-decreasing order. Equal keys therefore form one unbroken run in the output, and you can count a run by watching only the previous value.
This is the recursive inorder traversal pattern. The walk does the ordering for you, so the algorithm only keeps the previous value, the current run length, the best run length and the list of winners. When a problem gives you a BST and asks about repeated values or sorted order, try an inorder walk first.
Worked example
Input: root = [6,2,8,2,4,8,8,null,null,4,4] Output: [4,8] Explanation: The tree holds 2 twice, 4 three times, 6 once and 8 three times. The values 4 and 8 both reach the highest count of 3, so both are returned. The order of the output does not matter.
Approach 1: Brute force with a hash map
Visit every node once and count each value in a hash map. Then find the largest count and collect every key that has it. This works for any binary tree and ignores the BST rule. Its cost is the map, which can hold one entry per distinct value, so it can reach n entries.
Steps
- Create an empty hash map from value to count.
- Walk the whole tree, in any order, and visit every node.
- For each node, add one to the count of its value.
- Find the largest count stored in the map.
- Collect every key whose count equals that largest count.
Dry run
Walk the example in preorder: 6, 2, 2, 4, 4, 4, 8, 8, 8. The map fills up as {6: 1, 2: 2, 4: 3, 8: 3} in insertion order. The largest count is 3. The keys with count 3 are 4 and 8, so the output is [4, 8].
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the number of nodes. The walk runs the visit step once per node, and each map update takes O(1) average time, so the walk costs O(n). The map holds at most n entries and the recursion or explicit stack holds at most the height h, so the space is O(n).
Approach 2: Inorder list, then scan runs
What is slow: the map keeps a count for every distinct value, which is the O(n) extra space the follow-up forbids. The insight that fixes it: an inorder walk already yields values in sorted order, so equal values arrive together. Store the walked values in a list, then measure each run of equal values in that list. This removes the map, but the list still holds n values, so the next approach removes the list too.
Steps
- Walk the tree in order and append each value to a list.
- Start a pointer i at index 0.
- Move a second pointer j forward while the values equal values[i], to find where the run ends.
- Compare the run length j minus i with the best length so far, and update the modes list the same way as before.
- Set i to j and repeat until the list ends.
Dry run
The inorder list for the example is [2, 2, 4, 4, 4, 6, 8, 8, 8]. The run of 2s has length 2, so best becomes 2 and modes becomes [2]. The run of 4s has length 3, so modes becomes [4], and the run of 6 has length 1 and is ignored. The run of 8s has length 3, which ties the best, so modes becomes [4, 8].
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the number of nodes. The inorder walk visits each node once, which costs O(n). The run scan moves j forward across the list and sets i to j, so each index is passed a constant number of times, which costs O(n) in total. The list stores n values, so the space is O(n) plus O(h) for the recursion or stack.
PythonTested in our runner
from typing import List, Optional
class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
# Iterative inorder walk, so deep skewed trees do not hit the recursion limit
values = []
stack = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
values.append(node.val)
node = node.right
modes = []
best = 0
i = 0
while i < len(values):
j = i
while j < len(values) and values[j] == values[i]:
j += 1
run = j - i
if run > best:
best = run
modes = [values[i]]
elif run == best:
modes.append(values[i])
i = j
return modesThe Recursive Inorder Traversal infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Recursive Inorder Traversal
Approach 3: One-pass inorder with running countsOptimalRecursive Inorder Traversal
What is slow: the list in the previous approach stores every value, yet the scan only ever looks at the previous value and the current run. The insight that fixes it: run the counting logic during the inorder walk. Each node arrives after its predecessor in sorted order, so you compare it with prev and update three numbers right away. The only growing structure left is the modes list, which is the output.
Why it is correct. The walk visits keys in non-decreasing order, so all copies of a value are consecutive and never split. When the run for a value ends, its total count is final, so comparing it with best cannot miss a winner. Every value with the top frequency gets its full run counted, and ties are appended, so the modes list is complete.
Steps
- Set prev to nothing, count to 0, best to 0 and modes to an empty list.
- Walk the left subtree first.
- At the node, if its value equals prev, add one to count. Otherwise set count to 1.
- Set prev to the node's value.
- If count is greater than best, set best to count and replace modes with this value. If count equals best, append this value to modes.
- Walk the right subtree, then return modes.
Dry run
The inorder order of the example is 2, 2, 4, 4, 4, 6, 8, 8, 8. The table shows the state after each visit.
| Step | Visited | prev before | count | best | modes after |
|---|---|---|---|---|---|
| 1 | 2 | none | 1 | 1 | [2] |
| 2 | 2 | 2 | 2 | 2 | [2] |
| 3 | 4 | 2 | 1 | 2 | [2] |
| 4 | 4 | 4 | 2 | 2 | [2, 4] |
| 5 | 4 | 4 | 3 | 3 | [4] |
| 6 | 6 | 4 | 1 | 3 | [4] |
| 7 | 8 | 6 | 1 | 3 | [4] |
| 8 | 8 | 8 | 2 | 3 | [4] |
| 9 | 8 | 8 | 3 | 3 | [4, 8] |
The final modes list is [4, 8], which matches the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) extra space beyond the recursion stack, which is O(h) |
Let n be the number of nodes. Each node is visited once, and each visit does a fixed number of comparisons and assignments, so the time is O(n). The counters take constant space, and the stack holds at most h frames, where h is the tree height, so the extra space is O(h). The modes list is the output and is not counted, and on a skewed tree h equals n.
PythonTested in our runner
from typing import List, Optional
class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
# Explicit stack instead of recursion, because a skewed tree can be 10^4 levels deep
stack = []
node = root
prev = None
count = 0
best = 0
modes = []
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
# Compare with the previous value before updating prev
if node.val == prev:
count += 1
else:
count = 1
prev = node.val
if count > best:
best = count
modes = [node.val]
elif count == best:
modes.append(node.val)
node = node.right
return modesCommon mistakes
- Updating
prev = node.valbefore the comparison. Every node then equals itself, so count grows to n. Compare first, then set prev. - Writing
if count > bestwith noelif count == bestbranch. Ties such as 4 and 8 in the example get dropped, and the output becomes [4]. Add the equal branch. - Appending to
modesin the new-best branch. When best rises to 3, the old winners such as 2 stay in the list. Replace the list with a fresh one that holds only the current value. - Starting with
prev = 0instead of nothing. A first node with value 0 then looks like a repeat, and its count becomes 2 instead of 1. Use None, or a flag that says whether a previous value exists. - Comparing two Java
Integerobjects with==. That compares references, and values outside the cache range of -128 to 127 can fail. Compare withequals, or keep prev as a primitive plus a flag.
Edge cases
- A single node
[0]returns [0], because its count of 1 ties with the best of 1. - Three copies of 5 in a chain return [5], because the whole tree is one run.
- Distinct values such as [1, 2, 3] give every value a count of 1, so the output lists all of them in sorted order.
- Values -100000 and 100000 can both appear with count 1. Both must be returned, and no language should overflow or lose the sign.
- A skewed chain of 10^4 nodes drives the recursion depth to 10^4. Python needs the iterative walk here, because the default recursion limit is far lower.
- A tie that appears only at the end of the walk, such as the final run of 8s in the example, must still be added to the modes list.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Find Mode in Binary Search Tree, with how to answer them.
Unlock the follow-upsFind Mode in Binary Search Tree FAQ
What is the time complexity of Find Mode in Binary Search Tree?
The one-pass inorder solution runs in O(n) time, where n is the number of nodes. Each node is visited once and does constant work. The hash map brute force also runs in O(n) time on average.
Why use inorder traversal for Find Mode in Binary Search Tree?
An inorder walk of a BST visits values in sorted order, so equal values form one run. You count each run by comparing only with the previous value. This removes the need for a hash map of counts.
Can Find Mode in Binary Search Tree be solved in O(1) extra space?
Yes, if you exclude the recursion or explicit stack, which the follow-up allows. The one-pass solution uses a fixed number of variables. Counting the stack, the space is O(h). Morris traversal reaches O(1) including the stack by temporarily rewiring child pointers, but it is harder to write.
Does BFS work for Find Mode in Binary Search Tree?
Yes, a level-order walk with a hash map finds the modes. A BFS does not visit values in sorted order, so the run-counting trick does not apply. You need the map in that case, which costs O(n) space.
Why does the recursive Python solution fail on deep trees?
Python's default recursion limit is about 1000 frames. A skewed tree with 10^4 nodes goes far past that limit and raises an error. Use an explicit stack in Python so the depth does not grow the call stack.
Asked at
See which companies ask this — Pro
Related problems
- Binary Tree Inorder Traversal · same technique: Recursive Inorder Traversal
- Minimum Absolute Difference in BST · same technique: Recursive Inorder Traversal
- Validate Binary Search Tree · same technique: Recursive Inorder Traversal
- Kth Smallest Element in a BST · same technique: Recursive Inorder Traversal
- Delete Node in a BST · same technique: Recursive Inorder Traversal
- Same Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Balanced Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Diameter of Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Invert Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Maximum Depth of Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)