Find Mode In Binary Search Tree Problem
Description
LeetCode Problem 501.
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.
If the tree has more than one mode, return them in any order.
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than or equal to the node's key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
- Both the left and right subtrees must also be 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
Solution
Approach: In-Order Traversal with a Running Count
Counting every value in a hash map works for any tree, but it ignores the BST property and uses O(n) extra space. In a BST, an in-order traversal (left subtree, node, right subtree) visits the values in sorted order. Then all copies of a value are visited one right after another, so it is enough to count runs of equal values.
Keep four things during the traversal:
prev: the value visited just before,count: how many times in a rowprevhas appeared so far,maxCount: the longest run seen so far,modes: the values whose run reachedmaxCount.
When visiting a value:
- If it equals
prev, increasecount. Otherwise it starts a new run: setprevto it andcount = 1. - If
count > maxCount, this value is the only best so far: setmaxCount = countand resetmodesto just this value. - Else if
count == maxCount, it ties the best: append it tomodes.
The reset in step 2 is the detail that matters. For the in-order values 1, 2, 2, 1 first enters modes with a run of 1. Then the second 2 makes a run of 2 and replaces the list with [2]. No value is added twice: once its run ties maxCount, one more copy makes the run longer and resets the list to just that value.
Complexity: O(n) time, where n is the number of nodes, and O(h) space for the recursion, where h is the height of the tree (besides the output).
class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
self.prev = 0 # the value visited just before (meaningful once count > 0)
self.count = 0 # how many times in a row prev has appeared
self.max_count = 0
self.modes = []
self.inorder(root)
return self.modes
def inorder(self, node: Optional[TreeNode]) -> None:
# An in-order traversal of a BST visits the values in sorted order, so equal values come together.
if node is None:
return
self.inorder(node.left)
self.visit(node.val)
self.inorder(node.right)
def visit(self, val: int) -> None:
if self.count > 0 and val == self.prev:
self.count += 1
else:
self.prev = val
self.count = 1
if self.count > self.max_count:
self.max_count = self.count
self.modes = [val] # a new best: earlier modes no longer count
elif self.count == self.max_count:
self.modes.append(val)