Node Value Spanning the Most Tree Depths
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given the root of a binary tree where each node stores a hashable, non-None value val (such as a string or integer). Nodes at equal hop distance from root form a horizontal depth level: root sits at depth 0, its children sit at depth 1, their children sit at depth 2, and so on.
For each distinct value in the tree, define its depth span as the count of distinct depth levels that contain at least one node with that value. Multiple nodes carrying the same value on the same depth level contribute only 1 toward its depth span.
Implement value_on_most_levels(root: Optional[TreeNode]) -> Optional[Any] to return the value with the largest depth span:
- If
rootisNone, returnNone. - If two or more values tie for the highest depth span, return whichever tied value appears earliest in standard top-to-bottom, left-to-right level-order traversal.
Examples
Example 1
"R" (depth 0)
/ \
"G" "R" (depth 1)
/ \ \
"B" "B" "B" (depth 2)
- Input:
rootbuilt in level order from["R", "G", "R", "B", "B", None, "B"] - Output:
"R" - Explanation:
"R"appears at depths0and1(2distinct depths)."G"appears only at depth1(1depth). Even though"B"occupies three nodes in total, all three sit at depth2, giving"B"a depth span of1.
Example 2
7 (depth 0)
/ \
4 9 (depth 1)
/ \
9 4 (depth 2)
- Input:
rootbuilt in level order from[7, 4, 9, 9, 4] - Output:
4 - Explanation: Value
7spans1depth (0), while both4and9span2depths (1and2). Level-order traversal (7, 4, 9, 9, 4) visits4before9at depth1, so4wins the tie.
Constraints
0 <= number of nodes <= 10^50 <= tree height <= 10^5(the tree is not guaranteed to be balanced)- Every
node.valis hashable andnode.val is not None(falsy values such as0,"", orFalseare valid).
Step-by-step walkthrough
Restate the problem and visualize depth spans
Every node in a binary tree sits at a horizontal depth level (
root= depth0, its children = depth1, and so on). For each distinct value in the tree, we want to count how many different depth levels contain at least one copy of that value—not how many total nodes hold it:Depth 0: "R" -> distinct values here: {"R"} / \ Depth 1: "G" "R" -> distinct values here: {"G", "R"} / \ \ Depth 2: "B" "B" "B" -> distinct values here: {"B"} (extra "B"s on same depth are ignored!) Scores: "R" -> 2 depths (depths 0 and 1) "G" -> 1 depth (depth 1) "B" -> 1 depth (depth 2, even though "B" appears on 3 nodes!) Winner: "R"Two boundary rules complete the specification: an empty tree (
root is None) returnsNone, and any tie goes to whichever tied value appears earliest in top-to-bottom, left-to-right level order.Our function signature uses a standard
TreeNodeclass:from typing import Any, Optional class TreeNode: def __init__(self, val: Any, left: Optional["TreeNode"] = None, right: Optional["TreeNode"] = None) -> None: self.val = val self.left = left self.right = right def value_on_most_levels(root: Optional[TreeNode]) -> Optional[Any]: ...Why simpler traversals fall short
Before choosing our algorithm, let's check two natural first attempts:
- One tree scan per distinct value (
O(U * N)time): If we first collect allUdistinct values and then traverse theN-node tree separately for each value, mostly unique values (U ≈ N = 10^5) cause10^10steps. - Recursive depth-first search (DFS) storing
value -> set of depths: Walking down branches recursively and addingdepthtodepths_by_value[node.val]runs inO(N)time, which is fast. However, it has two practical downsides:- Extra memory: On a 100,000-node chain alternating
'X'and'Y', it stores 100,000 depth integers in sets even though there are only 2 distinct values. - Stack overflow: A skewed tree of depth 100,000 exceeds Python's default recursion limit (~1,000 frames) and crashes with
RecursionError.
- Extra memory: On a 100,000-node chain alternating
Can we visit every node once without recursion AND avoid storing every
(value, depth)pair?- One tree scan per distinct value (
Key idea: visit one level at a time with iterative BFS
Breadth-first search (BFS) explores a tree layer by layer—all nodes on level 1, then all nodes on level 2, then all nodes on level 3. Visiting all nodes of one level together makes deduplicating within a level effortless:
- Start a fresh empty set
seen_on_levelat the beginning of each level. - For each
nodeoncurrent_level:- If
node.valis not inseen_on_level, add it toseen_on_leveland add+1tolevel_counts[node.val]. - If
node.valis already inseen_on_level, skip incrementing—we already gave it credit for this level!
- If
- Collect all non-
Noneleft and right children intonext_level, then throwseen_on_levelaway when moving down.
Between levels, we only keep one integer counter per distinct value (
level_counts) plus the list of nodes on the current frontier!- Start a fresh empty set
Write the level-by-level loop
Instead of a single queue where two levels mix together, holding
current_levelas a Python list and buildingnext_levelin a loop gives a crisp boundary between levels with zero extra(node, depth)tuple overhead:def value_on_most_levels(root: Optional[TreeNode]) -> Optional[Any]: if root is None: return None # level_counts: maps node_value -> distinct depth levels containing it, e.g. {'R': 2, 'G': 1, 'B': 1}. level_counts = {} current_level = [root] while current_level: # seen_on_level: fresh set per depth so duplicate values on the same level count once seen_on_level = set() next_level = [] for node in current_level: if node.val not in seen_on_level: seen_on_level.add(node.val) level_counts[node.val] = level_counts.get(node.val, 0) + 1 if node.left is not None: next_level.append(node.left) if node.right is not None: next_level.append(node.right) current_level = next_level ...Pick the winner and justify correctness
Once all levels are processed, we scan
level_countsto find the highest count. Two small details make this scan bug-free:- Deterministic tie-breaking: Python
dictobjects preserve insertion order. Because BFS visits nodes top to bottom, left to right, keys enterlevel_countsin exact level-order first appearance. Updatingbest_valueonly on strictcount > best_countensures the earliest value wins any tie. - Safe handling of falsy values (
0,"",False): We initializebest_count = 0and testcount > best_count(neverif not best_value:). Because every key inlevel_countsappeared on at least1level (1 > 0), even a node value of0or""cleanly becomesbest_value.
Why this algorithm is guaranteed to be correct (loop invariant): - Claim: After
diterations of thewhileloop,current_levelholds every node at depthd + 1, and for every valuev,level_counts.get(v, 0)equals the exact number of levels in1..dthat containv. - Base case (d = 0): Before the loop,current_level = [root](all nodes at depth 1) andlevel_countsis empty (0levels counted in1..0). - Inductive step: On iterationd + 1,seen_on_levelstarts empty. Ifvappears one or more times incurrent_level, the first occurrence insertsvintoseen_on_leveland adds1tolevel_counts[v], while every subsequent copy on that same level seesv in seen_on_leveland adds0. Values absent from depthd + 1are unchanged. Meanwhile,next_levelgathers every child of depthd + 1, which is the exact set of nodes at depthd + 2. - Termination: Because a finite tree of heightHhas no nodes at depthH + 1,current_levelbecomes[]afterHiterations, at which pointlevel_counts[v]equals the total distinct levels containingvacross the entire tree.- Deterministic tie-breaking: Python
Trace Sample 1 level by level
Let's trace Sample 1 (
root = "R", depth 1"G", "R", depth 2"B", "B", "B"):Start: current_level = ["R"], level_counts = {} Iteration 1 (Depth 0): node "R" -> not in seen_on_level -> seen = {'R'}, level_counts = {'R': 1} children added to next_level: ["G", "R"] Iteration 2 (Depth 1): seen_on_level reset to set() node "G" -> not in seen -> seen = {'G'}, level_counts = {'R': 1, 'G': 1} node "R" -> not in seen -> seen = {'G', 'R'}, level_counts = {'R': 2, 'G': 1} children added to next_level: ["B", "B", "B"] Iteration 3 (Depth 2): seen_on_level reset to set() 1st "B" -> not in seen -> seen = {'B'}, level_counts = {'R': 2, 'G': 1, 'B': 1} 2nd "B" -> ALREADY in seen -> skipped! level_counts stays {'R': 2, 'G': 1, 'B': 1} 3rd "B" -> ALREADY in seen -> skipped! level_counts stays {'R': 2, 'G': 1, 'B': 1} children added to next_level: [] Loop ends (current_level is []). Winner scan over {'R': 2, 'G': 1, 'B': 1}: 'R' (2 > 0) -> best = 'R' (2) 'G' (1 > 2 False) 'B' (1 > 2 False) Return 'R'.Complete solution
from typing import Any, Optional class TreeNode: def __init__(self, val: Any, left: Optional["TreeNode"] = None, right: Optional["TreeNode"] = None) -> None: self.val = val self.left = left self.right = right def value_on_most_levels(root: Optional[TreeNode]) -> Optional[Any]: if root is None: return None # Phase 1: Traverse the binary tree one depth level at a time (iterative BFS). # level_counts: maps node_value -> distinct depth levels containing it, e.g. {'R': 2, 'G': 1, 'B': 1}. # Python dicts preserve insertion order, which records first-seen level order for ties. level_counts = {} current_level = [root] while current_level: # seen_on_level: fresh set per depth so duplicate values on the same level count once seen_on_level = set() next_level = [] for node in current_level: if node.val not in seen_on_level: seen_on_level.add(node.val) level_counts[node.val] = level_counts.get(node.val, 0) + 1 if node.left is not None: next_level.append(node.left) if node.right is not None: next_level.append(node.right) current_level = next_level # Phase 2: Find the value with the highest level count. # Start best_count at 0 (not truthiness on best_value) so falsy values like 0 or "" can win, # and use strict `>` so ties keep the earliest value seen in level order. best_value = None best_count = 0 for value, count in level_counts.items(): if count > best_count: best_value = value best_count = count return best_value✅ Submit now — all tests should pass.
Intuition & how it works
Imagine an office building where each floor represents one depth level of the binary tree, and we want to know which first name appears on the most different floors—even if three people named "B" sit on Floor 2, Floor 2 only counts as 1 floor for "B". The cleanest way to take floor-by-floor attendance is to walk Floor 0 from left to right with a fresh scratchpad, check off each unique name once on a master scoreboard, throw away the scratchpad, and ride the elevator to the next floor.
A naive approach might count total node occurrences across the tree (which wrongly lets three "B" nodes on a single level beat "R" appearing on two separate levels) or run a recursive depth-first search (DFS) (a traversal that dives all the way down one branch before backtracking) storing a set of depths for every value. Recursive DFS uses O(N) pair storage even when only 2 distinct values exist and crashes with RecursionError on a skewed tree (a tree shaped like a long single-file chain) deeper than Python's ~1,000-call stack limit. Instead, iterative breadth-first search (BFS) (visiting nodes level by level from top to bottom) processes one entire level list at a time, using a temporary hash set (a collection with O(1) average membership checks) to deduplicate values within that level before moving down.
Walk through Sample 1 with Depth 0 ["R"], Depth 1 ["G", "R"], and Depth 2 ["B", "B", "B"]:
1. Depth 0 (["R"]): seen_on_level starts empty; 'R' is new on this floor, so level_counts becomes {'R': 1}.
2. Depth 1 (["G", "R"]): seen_on_level resets; both 'G' and 'R' are new on Floor 1, updating level_counts to {'R': 2, 'G': 1}.
3. Depth 2 (["B", "B", "B"]): seen_on_level resets; the first 'B' updates level_counts to {'R': 2, 'G': 1, 'B': 1}, while the second and third 'B' are already in seen_on_level and are ignored. Scanning level_counts returns 'R' with 2 depths.
Complexity
- Time: O(N) on average, where
Nis the number of nodes in the binary tree. Every node is appended to a level list once and visited once; at each node we perform a constant number of hash set and dictionary lookups/updates (O(1)average time per hashable value), followed by a singleO(U)pass over theU <= Ndistinct values. - Space: O(W + U), where
Wis the maximum width of any single level (at mostN, e.g.,(N + 1) // 2on a complete binary tree and1on a chain) andUis the number of distinct values in the tree (U <= N). At any moment we hold onlycurrent_level,next_level,seen_on_level(all bounded byO(W)), andlevel_counts(O(U)).
Edge cases
- Empty tree (
root is None): Handled immediately at the top by returningNone. - Single-node tree: Runs one BFS iteration and returns
root.valwithbest_count = 1. - High frequency on a single level: Four
'Y'nodes on level 3 still score1, losing to'X'appearing once on level 1 and once on level 2 (score2). - Ties between multiple values: Because Python
3.7+dictionaries preserve insertion order and BFS visits nodes top to bottom, left to right, using strictcount > best_countdeterministically returns whichever tied value appeared earliest in level order. - Falsy node values (
0,"",False): A falsy value is a valid Python value like0or""that evaluates toFalsein anif value:check. Comparingcount > best_countstarting frombest_count = 0ensures0(1 > 0) is returned rather than mistaken forNone. - Deeply skewed chain (
100,000nodes): Because our BFS uses awhileloop instead of recursion, call-stack depth staysO(1)and never raisesRecursionError.
Common mistakes
- Counting total occurrences instead of distinct levels: Forgetting
seen_on_levelturns the problem into "most frequent value in the tree," failing whenever one level contains duplicate values like["B", "B", "B"]. - Using a single
seenset across the whole traversal: Declaringseen = set()outsidewhile current_level:instead of resetting it per level caps every value's score at1. - Mixing two levels inside a single queue: Pushing children onto a
dequewithout looping over the exact snapshot sizelen(queue)of the current level blurs where one floor ends and the next begins, breakingseen_on_level. - Unbounded recursion on skewed trees: Writing a recursive
dfs(node, depth)hits Python's recursion limit (~1,000) when a tree degenerates into a long linked list.
Alternative approaches
- Iterative DFS with a
(value, depth)hash set (O(N)time,O(N)space): Push(node, depth)pairs onto an explicit stack, insert(node.val, depth)into a global setseen_pairs, and count how many pairs eachvalueowns. This avoids recursion limits, though it can use more memory (O(N)pairs vsO(W + U)) when a deep narrow tree repeats only a few distinct values across many depths. Note that storing onlylast_seen_depth[val]does not work in DFS, because DFS jumps up and down between depths out of order!
Follow-up questions
- How would you adapt the function to return every value tied for the maximum level count, ordered by first level-order appearance? Keep Phase 1 completely unchanged, compute
max_levels = max(level_counts.values()), and return[val for val, cnt in level_counts.items() if cnt == max_levels]. Becauselevel_countspreserves insertion order, the tied winners come out cleanly ordered by their first appearance in level order inO(N)total time. - What modifications are needed if the input is a general k-ary tree or a directed graph that may contain cycles? For a k-ary tree, replace the
node.left/node.rightchecks withfor child in node.children:. For a directed graph starting from a source vertexs, define a vertex's level as its shortest-path hop count froms: maintain a globalvisited_nodes = {s}set when pushing neighbors intonext_levelso cycles never loop infinitely and each reachable vertex belongs to its single shortest-distance level inO(V + E)time. - How would you compute the winning value if billions of tree nodes were stored as rows in a distributed data warehouse? If each row already stores
(node_id, value, depth), run a two-stage distributed aggregation (Spark or MapReduce): emit(value, depth), deduplicate identical(value, depth)pairs locally in each partition combiner, group byvalueto count distinct depths per value, and pick the global maximum. If rows only store(node_id, parent_id, value)withoutdepth, compute depths first using pointer jumping (doubling ancestor hop distances each pass so heights up toDconverge inO(log D)distributed joins rather thanO(D)sequential passes).
Follow-up questions
- How would you adapt the function to return every value tied for the maximum level count, ordered by first level-order appearance?
- What modifications are needed if the input is a general k-ary tree or a directed graph that may contain cycles?
- How would you compute the winning value if billions of tree nodes were stored as rows in a distributed data warehouse?
Similar questions
- Hardening Stateful Grid Logic Against Malformed Inputs
- Dynamic Integer Stream Median
- Minimum Slots for Cooldown Task Scheduling
- Kubernetes Crash Triage, Health Probes, and Python ETL Review
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger