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 root is None, return None.
  • 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: root built in level order from ["R", "G", "R", "B", "B", None, "B"]
  • Output: "R"
  • Explanation: "R" appears at depths 0 and 1 (2 distinct depths). "G" appears only at depth 1 (1 depth). Even though "B" occupies three nodes in total, all three sit at depth 2, giving "B" a depth span of 1.

Example 2

        7            (depth 0)
       / \
      4   9          (depth 1)
     / \
    9   4            (depth 2)
  • Input: root built in level order from [7, 4, 9, 9, 4]
  • Output: 4
  • Explanation: Value 7 spans 1 depth (0), while both 4 and 9 span 2 depths (1 and 2). Level-order traversal (7, 4, 9, 9, 4) visits 4 before 9 at depth 1, so 4 wins the tie.

Constraints

  • 0 <= number of nodes <= 10^5
  • 0 <= tree height <= 10^5 (the tree is not guaranteed to be balanced)
  • Every node.val is hashable and node.val is not None (falsy values such as 0, "", or False are valid).

Step-by-step walkthrough

  1. Restate the problem and visualize depth spans

    Every node in a binary tree sits at a horizontal depth level (root = depth 0, its children = depth 1, 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) returns None, 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 TreeNode class:

    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]:
        ...
    
  2. Why simpler traversals fall short

    Before choosing our algorithm, let's check two natural first attempts:

    1. One tree scan per distinct value (O(U * N) time): If we first collect all U distinct values and then traverse the N-node tree separately for each value, mostly unique values (U ≈ N = 10^5) cause 10^10 steps.
    2. Recursive depth-first search (DFS) storing value -> set of depths: Walking down branches recursively and adding depth to depths_by_value[node.val] runs in O(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.

    Can we visit every node once without recursion AND avoid storing every (value, depth) pair?

  3. 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:

    1. Start a fresh empty set seen_on_level at the beginning of each level.
    2. For each node on current_level:
      • If node.val is not in seen_on_level, add it to seen_on_level and add +1 to level_counts[node.val].
      • If node.val is already in seen_on_level, skip incrementing—we already gave it credit for this level!
    3. Collect all non-None left and right children into next_level, then throw seen_on_level away 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!

  4. Write the level-by-level loop

    Instead of a single queue where two levels mix together, holding current_level as a Python list and building next_level in 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
        ...
    
  5. Pick the winner and justify correctness

    Once all levels are processed, we scan level_counts to find the highest count. Two small details make this scan bug-free:

    • Deterministic tie-breaking: Python dict objects preserve insertion order. Because BFS visits nodes top to bottom, left to right, keys enter level_counts in exact level-order first appearance. Updating best_value only on strict count > best_count ensures the earliest value wins any tie.
    • Safe handling of falsy values (0, "", False): We initialize best_count = 0 and test count > best_count (never if not best_value:). Because every key in level_counts appeared on at least 1 level (1 > 0), even a node value of 0 or "" cleanly becomes best_value.

    Why this algorithm is guaranteed to be correct (loop invariant): - Claim: After d iterations of the while loop, current_level holds every node at depth d + 1, and for every value v, level_counts.get(v, 0) equals the exact number of levels in 1..d that contain v. - Base case (d = 0): Before the loop, current_level = [root] (all nodes at depth 1) and level_counts is empty (0 levels counted in 1..0). - Inductive step: On iteration d + 1, seen_on_level starts empty. If v appears one or more times in current_level, the first occurrence inserts v into seen_on_level and adds 1 to level_counts[v], while every subsequent copy on that same level sees v in seen_on_level and adds 0. Values absent from depth d + 1 are unchanged. Meanwhile, next_level gathers every child of depth d + 1, which is the exact set of nodes at depth d + 2. - Termination: Because a finite tree of height H has no nodes at depth H + 1, current_level becomes [] after H iterations, at which point level_counts[v] equals the total distinct levels containing v across the entire tree.

  6. 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'.
    
  7. 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 N is 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 single O(U) pass over the U <= N distinct values.
  • Space: O(W + U), where W is the maximum width of any single level (at most N, e.g., (N + 1) // 2 on a complete binary tree and 1 on a chain) and U is the number of distinct values in the tree (U <= N). At any moment we hold only current_level, next_level, seen_on_level (all bounded by O(W)), and level_counts (O(U)).

Edge cases

  • Empty tree (root is None): Handled immediately at the top by returning None.
  • Single-node tree: Runs one BFS iteration and returns root.val with best_count = 1.
  • High frequency on a single level: Four 'Y' nodes on level 3 still score 1, losing to 'X' appearing once on level 1 and once on level 2 (score 2).
  • Ties between multiple values: Because Python 3.7+ dictionaries preserve insertion order and BFS visits nodes top to bottom, left to right, using strict count > best_count deterministically returns whichever tied value appeared earliest in level order.
  • Falsy node values (0, "", False): A falsy value is a valid Python value like 0 or "" that evaluates to False in an if value: check. Comparing count > best_count starting from best_count = 0 ensures 0 (1 > 0) is returned rather than mistaken for None.
  • Deeply skewed chain (100,000 nodes): Because our BFS uses a while loop instead of recursion, call-stack depth stays O(1) and never raises RecursionError.

Common mistakes

  • Counting total occurrences instead of distinct levels: Forgetting seen_on_level turns the problem into "most frequent value in the tree," failing whenever one level contains duplicate values like ["B", "B", "B"].
  • Using a single seen set across the whole traversal: Declaring seen = set() outside while current_level: instead of resetting it per level caps every value's score at 1.
  • Mixing two levels inside a single queue: Pushing children onto a deque without looping over the exact snapshot size len(queue) of the current level blurs where one floor ends and the next begins, breaking seen_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 set seen_pairs, and count how many pairs each value owns. This avoids recursion limits, though it can use more memory (O(N) pairs vs O(W + U)) when a deep narrow tree repeats only a few distinct values across many depths. Note that storing only last_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]. Because level_counts preserves insertion order, the tied winners come out cleanly ordered by their first appearance in level order in O(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.right checks with for child in node.children:. For a directed graph starting from a source vertex s, define a vertex's level as its shortest-path hop count from s: maintain a global visited_nodes = {s} set when pushing neighbors into next_level so cycles never loop infinitely and each reachable vertex belongs to its single shortest-distance level in O(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 by value to count distinct depths per value, and pick the global maximum. If rows only store (node_id, parent_id, value) without depth, compute depths first using pointer jumping (doubling ancestor hop distances each pass so heights up to D converge in O(log D) distributed joins rather than O(D) sequential passes).

Follow-up questions

Similar questions

More IXL Learning interview questions

All 5 IXL Learning questions →