Given the root
of a Binary Search Tree (BST), find the mode(s) (i.e., the most frequently occurred element) in the BST.
Constraints:
[1, 10^4]
.-10^5 <= Node.val <= 10^5
The strategy involves:
collections.Counter
) to count the frequency of each value.from typing import Optional, List
from collections import Counter
# Definition for a binary tree node
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def findMode(root: Optional[TreeNode]) -> List[int]:
if not root:
return []
# Helper function to perform in-order traversal
def inOrderTraversal(node, freq):
if not node:
return
inOrderTraversal(node.left, freq)
freq[node.val] += 1
inOrderTraversal(node.right, freq)
# Frequency dictionary
freq = Counter()
# Populate the frequency dictionary
inOrderTraversal(root, freq)
# Find the maximum frequency
max_freq = max(freq.values())
# Collect all the values that have the maximum frequency
mode = [val for val, count in freq.items() if count == max_freq]
return mode
The time complexity of this approach is (O(n)), where (n) is the number of nodes in the BST.
Therefore, the overall time complexity is (O(n)).
The space complexity is also (O(n)).
Counter
will store up to (n) different values in the worst case.Thus, considering both the Counter and the recursion stack, the total space complexity is (O(n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?