Mode of a ternary search tree
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's first round (coding), last asked Nov 2025. It tests trees and dfs.
Each node of this tree has up to three children: left holds values smaller than the node's, middle holds values equal to it, and right holds values larger. Return the mode: the value or values that occur most often among all nodes. Then handle a tree that breaks those ordering rules.
Interface
Unless you agree on a different interface with the interviewer, assume:
class Node: val: int; left, middle, right: Node | None-
tree_modes(root: Node | None) -> list[int]— every value tied for the highest count, in increasing order;[]for an empty tree.
Example
5
/ | \
3 5 7
| |
3 5
tree_modes(root) -> [5] # 5 three times, 3 twice, 7 once
If the second 5 (under the middle) were removed, 3 and 5 would tie at two each, giving [3, 5]. A single node with value 42 gives [42].
Constraints
- Up to 10^5 nodes; values are 32-bit signed integers.
- The tree is deep enough that recursion may overflow the stack.
Clarifying questions
- Do equal values always go to
middle, or can they appear elsewhere? - With a tie, return all modes or any one? In what order?
- Can I use O(n) extra space, or should it be O(1) beyond the traversal?
- How deep can the tree be?
What a strong answer covers
- In a valid tree, an in-order walk (left, node, middle, right) visits values in non-decreasing order, so equal values are consecutive. Track the current run and the best run: O(n) time, O(h) space, no hash map.
- An iterative traversal with an explicit stack for deep trees.
- Ties: reset the result list when a longer run appears, append on an equal run.
- Part 2, a broken tree: equal values are no longer adjacent, so count with a hash map over any traversal, O(n) time and O(distinct values) space. Can you detect that the tree is broken while walking it?
- Tests: empty, one node, all equal, a long chain, ties.
Follow-ups
- Do the valid case in O(1) extra space (Morris-style threading).
- Return the k most frequent values.
- Nodes are inserted and removed over time; keep the mode current.
Where it's asked
- Google · First round: coding · Last asked Nov 202545 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
What it tests
trees · dfs
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
