Longest Root-to-Leaf Depth from Child Pairs

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Given an array-encoded binary tree children, compute the node count along its tallest path from the root down to a leaf.

For a tree containing n = len(children) nodes:

  • Node IDs run from 0 to n - 1. Whenever n >= 1, node 0 is the root.
  • Entry children[i] = [left_id, right_id] specifies node i's left and right child IDs, using -1 whenever a child slot is empty.
  • Depth measures nodes rather than edges: return 0 when children is empty ([]), and return 1 when the tree holds only root 0 ([[-1, -1]]).
def maximum_tree_depth(children: List[List[int]]) -> int:
    pass

Examples

Example 1

Input:  children = [[1, 2], [3, -1], [-1, 4], [-1, -1], [5, -1], [-1, -1]]
Output: 4

Walk-through: Root 0 branches to left child 1 and right child 2. Path 0 -> 1 -> 3 contains 3 nodes, whereas path 0 -> 2 -> 4 -> 5 contains 4 nodes, so the tallest root-to-leaf node count is 4.

Example 2

Input:  children = [[-1, 2], [-1, -1], [1, -1]]
Output: 3

Walk-through: Root 0 links on the right to node 2, which links on the left to leaf 1, forming a three-node chain 0 -> 2 -> 1 of depth 3.

Constraints

  • 0 <= len(children) <= 200,000
  • Each children[i] is a two-element list [left_id, right_id], where every entry is either -1 or an integer in [0, len(children) - 1].
  • Whenever children is non-empty, the links describe one connected, cycle-free binary tree rooted at 0 in which every node 1 .. n - 1 has a single parent.
  • Tree topology can be arbitrarily skewed (including a single 200,000-node chain); target O(n) runtime without overflowing the call stack.

Step-by-step walkthrough

  1. Understand the input array and depth rule

    Instead of TreeNode objects with .left and .right attributes, the tree arrives as a list of integer pairs named children:

    • Nodes carry IDs 0 through n - 1. Whenever children is non-empty, node 0 is always the root (the top node with no parent).
    • children[i] = [left_child, right_child] gives node i's child IDs, using -1 whenever that side has no child.
    • A leaf is a node whose left and right entries are both -1.

    Here is how Example 1 (children = [[1, 2], [3, -1], [-1, 4], [-1, -1], [5, -1], [-1, -1]]) maps from array indices to a binary tree:

    Index:  0        1         2         3         4         5
    Pair:  [1, 2]  [3, -1]  [-1, 4]   [-1, -1]  [5, -1]   [-1, -1]
    
    Tree:
              0          <-- Level 1 (root)
             / \
            1   2        <-- Level 2
           /     \
          3       4      <-- Level 3
                 /
                5        <-- Level 4 (deepest leaf)
    

    Depth counts nodes (not edges) along a tallest root-to-leaf path:

    • Empty tree ([]): 0 nodes, so return 0.
    • Single root ([[-1, -1]]): 1 node, so return 1.
    • Example 1: the tallest path 0 -> 2 -> 4 -> 5 visits 4 nodes, so return 4.
  2. Why plain recursion breaks on a deep chain

    The classic textbook formula computes a node's depth recursively: an absent child (-1) has depth 0, and any real node has depth 1 + max(depth(left), depth(right)).

    def recursive_depth(children: List[List[int]], node: int) -> int:
        if node == -1:
            return 0
        left_child, right_child = children[node]
        return 1 + max(
            recursive_depth(children, left_child),
            recursive_depth(children, right_child),
        )
    

    While this formula is clean and takes O(n) work, recursion pauses the parent function call on the call stack (the memory region tracking active, unfinished function calls) while it waits for its children to finish. Python caps the call stack at roughly 1,000 nested calls by default.

    Balanced tree (safe):         Skewed chain of 200,000 nodes (crashes!):
            0                         0 -> 1 -> 2 -> ... -> 199,999
          /   \                       (200,000 nested calls -> RecursionError)
         1     2
    

    Because n can reach 200,000 and every internal node might have just one child, recursion can dive 200,000 frames deep and crash with RecursionError. We need a loop-based approach that keeps ordinary lists in heap memory instead of nesting function calls.

  3. Key idea: count levels one layer at a time

    Every child sits one level deeper than its parent, so the tallest root-to-leaf node count equals the total number of non-empty horizontal layers in the tree!

    We can visit the tree one layer at a time using breadth-first search (BFS) — a traversal that explores all nodes at distance d from the root before advancing to distance d + 1:

    Start:   current_level = [0],     depth = 0
    Round 1: visit [0]     -> depth = 1, gather children -> next_level = [1, 2]
    Round 2: visit [1, 2]  -> depth = 2, gather children -> next_level = [3, 4]
    Round 3: visit [3, 4]  -> depth = 3, gather children -> next_level = [5]
    Round 4: visit [5]     -> depth = 4, gather children -> next_level = []
    Stop:    current_level is empty -> return depth (4)
    

    Every node belongs to a single layer, so we read each node's [left_child, right_child] pair once (O(n) total time) with zero recursion.

  4. Handle the empty tree and build each next layer

    Before starting at node 0, we check if not children: and immediately return 0. Without that guard, starting with current_level = [0] would try to read children[0] on an empty list and raise IndexError.

    Inside the loop, when scanning left_child, right_child = children[node], we must check != -1 before appending to next_level. In Python, this check is doubly important: -1 is a valid list index meaning "the last element", so accidentally appending -1 would read children[-1] on the next round instead of crashing loudly!

    def maximum_tree_depth(children: List[List[int]]) -> int:
        if not children:
            return 0
    
        current_level = [0]
        depth = 0
    
        while current_level:
            depth += 1
            next_level = []
    
            for node in current_level:
                left_child, right_child = children[node]
                if left_child != -1:
                    next_level.append(left_child)
                if right_child != -1:
                    next_level.append(right_child)
    
            current_level = next_level
    
        return depth
    
  5. Trace Example 1 step by step

    Let's trace children = [[1, 2], [3, -1], [-1, 4], [-1, -1], [5, -1], [-1, -1]] from start to finish:

    Initial state:
      current_level = [0], depth = 0
    
    Iteration 1 (current_level = [0] is non-empty):
      depth becomes 1
      node 0 -> children[0] = [1, 2] -> append 1, append 2
      current_level becomes [1, 2]
    
    Iteration 2 (current_level = [1, 2] is non-empty):
      depth becomes 2
      node 1 -> children[1] = [3, -1] -> append 3
      node 2 -> children[2] = [-1, 4] -> append 4
      current_level becomes [3, 4]
    
    Iteration 3 (current_level = [3, 4] is non-empty):
      depth becomes 3
      node 3 -> children[3] = [-1, -1] -> skip both
      node 4 -> children[4] = [5, -1]  -> append 5
      current_level becomes [5]
    
    Iteration 4 (current_level = [5] is non-empty):
      depth becomes 4
      node 5 -> children[5] = [-1, -1] -> skip both
      current_level becomes []
    
    Loop ends because current_level is empty -> return 4.
    

    Even if the input is a 200,000-node chain, each current_level holds just one integer, and the while loop ticks cleanly 200,000 times.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def maximum_tree_depth(children: List[List[int]]) -> int:
        # Phase 1: An empty list means the tree has 0 nodes, so its depth is 0.
        # Checking this first prevents indexing children[0] on an empty list.
        if not children:
            return 0
    
        # current_level: list of node IDs on the current depth layer, e.g. [1, 2].
        # Node 0 is always the root when the tree is non-empty.
        current_level = [0]
        depth = 0
    
        # Phase 2: Breadth-first (level-by-level) traversal.
        # Each non-empty layer of nodes adds 1 to the maximum root-to-leaf node count.
        while current_level:
            depth += 1
            # next_level: collects all valid children of nodes in current_level.
            next_level = []
    
            for node in current_level:
                left_child, right_child = children[node]
                # Check != -1 explicitly: -1 encodes a missing child, and in Python
                # children[-1] would silently read the last element instead of failing.
                if left_child != -1:
                    next_level.append(left_child)
                if right_child != -1:
                    next_level.append(right_child)
    
            current_level = next_level
    
        return depth
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of the binary tree as a multi-story office building where node 0 occupies the top floor, its direct children occupy one floor below, their children sit one floor below that, and so on. Because we want the node count along a tallest path from the root (the top node) down to a leaf (a node with no children), the answer equals the total number of occupied floors. Instead of diving down one branch and backtracking, we sweep across the tree one floor at a time using breadth-first search (BFS) — a traversal that visits every node on the current level before advancing to the next level.

The obvious textbook approach uses recursion (a function calling itself on left and right children and returning 1 + max(left_depth, right_depth)). While mathematically sound, every active recursive call occupies a frame on the call stack (the fixed-size memory area tracking unfinished function calls). In Python, the call stack stops around 1,000 nested calls by default, so a skewed chain of 200,000 nodes crashes with RecursionError. Replacing recursion with a while loop over the current floor's list of node IDs keeps everything in ordinary heap memory and handles any tree shape safely.

Let's trace Example 1 (children = [[1, 2], [3, -1], [-1, 4], [-1, -1], [5, -1], [-1, -1]]): 1. Start at current_level = [0] with depth = 0. 2. Floor 1 ([0]): Increment depth to 1. Read children[0] = [1, 2]; both are present (!= -1), so next_level becomes [1, 2]. 3. Floor 2 ([1, 2]): Increment depth to 2. Node 1 ([3, -1]) adds 3 and node 2 ([-1, 4]) adds 4, so next_level becomes [3, 4]. 4. Floor 3 ([3, 4]): Increment depth to 3. Node 3 ([-1, -1]) is a leaf while node 4 ([5, -1]) adds 5, so next_level becomes [5]. 5. Floor 4 ([5]): Increment depth to 4. Node 5 ([-1, -1]) adds nothing, making next_level = [] and returning 4.

Complexity

  • Time: O(n), where n = len(children) is the total node count. Because the input forms a connected acyclic tree rooted at 0, each node ID enters current_level in a single round, and we perform one O(1) list lookup (children[node]) plus at most two O(1) list appends per node.
  • Space: O(w), where w is the maximum width (the largest number of nodes on any single level), which is O(n) in the worst case. At any moment we only store current_level and next_level; for a single chain w = 1 (O(1) extra memory), while for a complete binary tree (every level filled except possibly the bottom) the bottom level holds up to (n + 1) // 2 nodes (O(n) memory).

Edge cases

  • Empty tree (children = []): Handled before touching children[0], returning 0.
  • Single-node tree (children = [[-1, -1]]): Enters the loop once with current_level = [0], sets depth = 1, builds next_level = [], and returns 1 (depth counts nodes, not edges).
  • Completely skewed chain (n = 200,000): Runs 200,000 loop iterations with 1 node per level and zero risk of overflowing the call stack.
  • Wide balanced tree (n = 200,000): Finishes in just 18 outer iterations (since 2^17 = 131,072 <= 200,000 < 262,144 = 2^18), exercising the widest next_level list.
  • Non-increasing node IDs (e.g., 0 -> 2 -> 1 in Example 2): Node IDs are only array indices, so following links from 0 works regardless of numbering order.
  • One-sided children ([left, -1] or [-1, right]): Missing sides (-1) are skipped independently.

Common mistakes

  • Using plain recursion without considering tree height: Works on small or balanced test cases, then raises RecursionError on a deep chain of 200,000 nodes.
  • Counting edges instead of nodes: Initializing depth = -1 or only counting transitions between levels returns 0 for a single-node tree and 3 instead of 4 for Example 1.
  • Forgetting the empty-tree check: Starting unconditionally with current_level = [0] raises IndexError when children is [].
  • Forgetting != -1 before indexing children: In Python, children[-1] does not raise an error — it reads the last element of children! Appending -1 into next_level silently jumps to node n - 1 and can cause an infinite loop.
  • Using list.pop(0) in a single-queue BFS: Removing element 0 from a Python list shifts every remaining element left in O(k) time, turning wide trees into O(n^2) time; use two level lists as shown here or collections.deque (a deque, or double-ended queue supporting O(1) appends and pops at both ends).

Alternative approaches

  • Iterative depth-first search (DFS) with an explicit stack: Push (0, 1) ((node_id, depth_so_far)) onto a Python list, pop the top pair in a while loop, update best_depth = max(best_depth, depth_so_far), and push any non--1 child with depth_so_far + 1. This also runs in O(n) time without recursion; its stack holds at most O(h) entries for a tree of height h (at most h + 1 on a skewed chain, and O(log n) on a balanced tree).
  • Single-queue BFS with collections.deque: Store (node_id, node_depth) pairs or iterate for _ in range(len(queue)): per level using queue.popleft(). Asymptotically identical (O(n) time, O(w) space), though swapping two plain Python lists per level has slightly less per-node overhead.

Follow-up questions

  • How would you modify the traversal to find the shortest root-to-leaf node count instead? Keep the exact same level-by-level BFS loop, and as soon as you inspect a node whose left_child == -1 and right_child == -1 (a true leaf), immediately return the current depth. Because BFS visits levels in strictly increasing order (1, 2, 3, ...), the very first leaf encountered is guaranteed to sit on a shortest root-to-leaf path, often letting you stop early without scanning deeper levels. Watch out for one-child nodes ([3, -1]): a node with one child is not a leaf, so you must keep going.
  • How could you detect malformed inputs such as cycles, shared children, or unreachable nodes? Maintain a visited = [False] * len(children) boolean list (with visited[0] = True initially) before starting the loop. Whenever you see a child index child != -1, check whether child lies outside 0 <= child < len(children) or visited[child] is already True: if so, either two parents share child or there is a cycle, so raise an error instead of looping forever. Once the while loop finishes, verify all(visited) to confirm every node was reachable from root 0.
  • How would you reconstruct the actual sequence of node IDs along a deepest root-to-leaf path? Keep a parent = [-1] * len(children) array and record parent[child] = node whenever you append child to next_level, while also saving deepest_leaf = current_level[0] before advancing current_level. Once the loop terminates, deepest_leaf sits on the bottommost layer; walk backward via cur = parent[cur] until cur == -1, collecting node IDs into a list, and reverse that list in O(n) total time and O(n) space.

Follow-up questions

Similar questions

More LinkedIn interview questions

All 154 LinkedIn questions →