#501
Find Mode in Binary Search Tree
EasyTreeDepth-First SearchBinary Search TreeBinary TreeHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses an in-order traversal to count occurrences while keeping track of the current value and its frequency. This allows us to find the modes in a single traversal of the tree, making it efficient.
⚙️
Algorithm
3 steps- 1Step 1: Perform an in-order traversal of the tree while counting occurrences of each value.
- 2Step 2: Keep track of the current value and its frequency during traversal.
- 3Step 3: Update the modes list when a new maximum frequency is found.
solution.py25 lines
1# Full working Python code
2from collections import defaultdict
3
4def findMode(root):
5 def inorder(node):
6 nonlocal current_val, current_count, max_count, modes
7 if not node:
8 return
9 inorder(node.left)
10 if node.val == current_val:
11 current_count += 1
12 else:
13 current_val = node.val
14 current_count = 1
15 if current_count > max_count:
16 max_count = current_count
17 modes = [current_val]
18 elif current_count == max_count:
19 modes.append(current_val)
20 inorder(node.right)
21
22 current_val, current_count, max_count = None, 0, 0
23 modes = []
24 inorder(root)
25 return modesℹ
Complexity note: This complexity is optimal because we only traverse the tree once, making it O(n), where n is the number of nodes. We use constant space for the mode tracking, not counting the output space.
- 1In-order traversal is key for BST problems.
- 2Tracking state (current value and count) helps optimize the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.