Identify Node Value Present Across Most Depth Levels
Trees & GraphsModel answerLast updated
Find the binary tree node value that appears across the highest number of unique depth levels.
Given the root of a binary tree whose nodes contain hashable values (e.g., characters or integers), determine which value is present across the maximum number of distinct depth levels.
For example, consider the following tree:
X
/ \
X Y
/ \
Z Z
- Value
Xappears at depth 0 (the root) and depth 1. Count of distinct levels = 2. - Value
Yappears only at depth 1. Count of distinct levels = 1. - Value
Zappears twice, but both occurrences are at depth 2. Count of distinct levels = 1.
The output for this tree should be 'X'.
Requirements
- Define clear rules for edge cases, such as an empty tree or ties between multiple values.
- Outline your algorithm, explain why it correctly tracks level counts, and state both time and memory complexities.
- Provide a working Python implementation.
Hints
Hint 1
Counting total node frequency is different from counting unique levels. Multiple occurrences of a value on the exact same depth level only count once.
Hint 2
If you use Breadth-First Search (BFS), nodes at depth `d` are processed sequentially before any node at depth `d + 1`.
Hint 3
Instead of storing a full set of visited levels for each value, can you track just the most recent level index at which a value was encountered?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and Intuition
To solve this problem, we must track the number of distinct depth levels occupied by each unique value.
A naive solution using Depth-First Search (DFS) or standard traversal would maintain a map of value -> set of levels. For every node (val, level), we insert level into set_of_levels[val]. At the end, the length of each set gives the distinct level count. However, this could use $O(N)$ space just for storing level indices when many duplicate values exist.
We can optimize space by conducting a Breadth-First Search (BFS) (level-order traversal).
Because BFS guarantees that all nodes at level $L$ are evaluated before any node at level $L+1$, we can process nodes level by level. Instead of storing every level index in a set, we only need to store two pieces of information per value:
level_count[val]: The number of distinct levelsvalhas appeared on so far.last_level_seen[val]: The index of the most recent level on whichvalwas observed.
When processing level $L$:
- If
last_level_seen[val] != L, this is the first time we encountervalat level $L$. We updatelast_level_seen[val] = Land incrementlevel_count[val]by 1. - If
last_level_seen[val] == L, we have already countedvalfor this level, so we ignore it.
Edge Case Policy & Tie-Breaking
- Empty Tree: Return
None. - Ties: If multiple values share the highest number of distinct levels, break ties deterministically by choosing the value that appeared earliest in a standard level-order (left-to-right) traversal.
Python Implementation
from collections import deque
from typing import Any, Optional
class TreeNode:
def __init__(self, val: Any, left: 'Optional[TreeNode]' = None, right: 'Optional[TreeNode]' = None):
self.val = val
self.left = left
self.right = right
def max_distinct_level_value(root: Optional[TreeNode]) -> Any:
if root is None:
return None
level_count = {} # value -> count of distinct levels
last_level_seen = {} # value -> level index of most recent occurrence
queue = deque([root])
current_level = 0
while queue:
nodes_at_level = len(queue)
for _ in range(nodes_at_level):
node = queue.popleft()
val = node.val
# Increment count only on first occurrence within current_level
if last_level_seen.get(val) != current_level:
last_level_seen[val] = current_level
level_count[val] = level_count.get(val, 0) + 1
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
current_level += 1
# Find value with max level count.
# Iterating over dict preserves insertion order (BFS order),
# so strict '>' naturally breaks ties by earliest appearance.
best_value = None
max_levels = 0
for val, count in level_count.items():
if count > max_levels:
max_levels = count
best_value = val
return best_value
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the total number of nodes in the binary tree. Every node is enqueued and dequeued exactly once. Hash table lookups and insertions operate in $\mathcal{O}(1)$ average time.
- Space Complexity: $\mathcal{O}(W + U)$, where $W$ is the maximum width of the binary tree (for the BFS queue) and $U$ is the number of unique node values (for the tracking hash maps). In the worst case, this is bounded by $\mathcal{O}(N)$. Space is optimized over the DFS set-based approach because each unique value only retains a single integer level index rather than a collection of all level indices.