Find Mode in Binary Search Tree (LeetCode 501): Solution and Explanation

Easy
Tree
Depth First Search
Binary Search Tree
Binary Tree

Given a binary search tree that may hold duplicate values, return every value that occurs the most times. If several values tie for the highest count, return all of them in any order.

Intuition

A hash map from value to count solves this for any binary tree, but it ignores the BST ordering and uses O(n) extra space.

An inorder traversal of a BST lists its values in sorted order. In a sorted list every copy of a value sits next to the others, so a value's frequency is just the length of its run.

That means only three numbers are needed while walking: the previous value, the length of the current run, and the longest run seen so far. The answer list changes only when a run catches up with or beats the longest one.

Approach: Inorder traversal counting runs

  1. Set prev = None, count = 0, best = 0 and modes = [].
  2. Walk the tree inorder: left subtree, node, right subtree.
  3. At each node, if its value equals prev add one to count, otherwise set count = 1 because a new run starts.
  4. If count > best, set best = count and restart modes as [val]. If count == best, append val to modes.
  5. Set prev = val, continue the walk, and return modes at the end.

Step-by-step example

root = [1,null,2,2]
  1. The inorder order is 1, 2, 2 (the second 2 is the left child of the first).
  2. Visit 1: a new run, count = 1. That beats best = 0, so best = 1 and modes = [1].
  3. Visit 2: a different value, count = 1. It ties best, so modes = [1, 2].
  4. Visit 2 again: equal to prev, count = 2. That beats best, so best = 2 and modes restarts as [2].
  5. The walk ends. Return [2].

Code: Python, Java, C++

1class Solution:
2    def findMode(self, root: Optional[TreeNode]) -> List[int]:
3        self.prev = None
4        self.count = 0
5        self.best = 0
6        self.modes = []
7
8        def inorder(node):
9            if not node:
10                return
11            inorder(node.left)
12            self.count = self.count + 1 if node.val == self.prev else 1
13            if self.count > self.best:
14                self.best = self.count
15                self.modes = [node.val]
16            elif self.count == self.best:
17                self.modes.append(node.val)
18            self.prev = node.val
19            inorder(node.right)
20
21        inorder(root)
22        return self.modes
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every node is visited once and does constant work.

Space

O(h)

The recursion stack is as deep as the tree height h. The modes list is the output and is not counted.

Other approaches

Hash map of counts (time O(n), space O(n))

Traverse in any order, count each value in a map, then return every value whose count equals the maximum. Works for any binary tree.

Two-pass inorder (time O(n), space O(h))

The first pass finds only the longest run length, the second collects the values with that run length. Avoids clearing a list, at the cost of a second walk.

Morris inorder traversal (time O(n), space O(1))

Thread the tree temporarily so the inorder walk needs no recursion stack, giving O(1) extra space for the follow-up question.

Common mistakes

  • Forgetting to clear the list when a longer run appears, which leaves old shorter-run values in the answer.
  • Using 0 or another number as the 'no previous value' marker. Any integer from -100000 to 100000 can appear in the tree.
  • Only updating the answer when a run ends. If the longest run is the last one in sorted order it is never closed, so update on every node instead.
  • Assuming duplicates only appear as left children. With this BST rule an equal value may be in either subtree, and inorder still keeps them together.

Frequently asked questions

Why does inorder keep equal values together?

Inorder visits a BST in non-decreasing order. In a sorted sequence, all copies of a value form one contiguous block, so no copy can appear after a larger value.

Does the order of the returned modes matter?

No, any order is accepted. The inorder walk happens to return them in increasing order.

How does this meet the follow-up of no extra space?

Apart from the recursion stack, it stores only prev, count and best. The recursion stack does not count toward the follow-up, and Morris traversal removes even that.