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
0ton - 1. Whenevern >= 1, node0is the root. - Entry
children[i] = [left_id, right_id]specifies nodei's left and right child IDs, using-1whenever a child slot is empty. - Depth measures nodes rather than edges: return
0whenchildrenis empty ([]), and return1when the tree holds only root0([[-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-1or an integer in[0, len(children) - 1]. - Whenever
childrenis non-empty, the links describe one connected, cycle-free binary tree rooted at0in which every node1 .. n - 1has a single parent. - Tree topology can be arbitrarily skewed (including a single
200,000-node chain); targetO(n)runtime without overflowing the call stack.
Step-by-step walkthrough
Understand the input array and depth rule
Instead of
TreeNodeobjects with.leftand.rightattributes, the tree arrives as a list of integer pairs namedchildren:- Nodes carry IDs
0throughn - 1. Wheneverchildrenis non-empty, node0is always the root (the top node with no parent). children[i] = [left_child, right_child]gives nodei's child IDs, using-1whenever 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 (
[]):0nodes, so return0. - Single root (
[[-1, -1]]):1node, so return1. - Example 1: the tallest path
0 -> 2 -> 4 -> 5visits4nodes, so return4.
- Nodes carry IDs
Why plain recursion breaks on a deep chain
The classic textbook formula computes a node's depth recursively: an absent child (
-1) has depth0, and any real node has depth1 + 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 2Because
ncan reach200,000and every internal node might have just one child, recursion can dive 200,000 frames deep and crash withRecursionError. We need a loop-based approach that keeps ordinary lists in heap memory instead of nesting function calls.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
dfrom the root before advancing to distanced + 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.Handle the empty tree and build each next layer
Before starting at node
0, we checkif not children:and immediately return0. Without that guard, starting withcurrent_level = [0]would try to readchildren[0]on an empty list and raiseIndexError.Inside the loop, when scanning
left_child, right_child = children[node], we must check!= -1before appending tonext_level. In Python, this check is doubly important:-1is a valid list index meaning "the last element", so accidentally appending-1would readchildren[-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 depthTrace 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_levelholds just one integer, and thewhileloop ticks cleanly 200,000 times.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), wheren = len(children)is the total node count. Because the input forms a connected acyclic tree rooted at0, each node ID enterscurrent_levelin a single round, and we perform oneO(1)list lookup (children[node]) plus at most twoO(1)list appends per node. - Space:
O(w), wherewis the maximum width (the largest number of nodes on any single level), which isO(n)in the worst case. At any moment we only storecurrent_levelandnext_level; for a single chainw = 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) // 2nodes (O(n)memory).
Edge cases
- Empty tree (
children = []): Handled before touchingchildren[0], returning0. - Single-node tree (
children = [[-1, -1]]): Enters the loop once withcurrent_level = [0], setsdepth = 1, buildsnext_level = [], and returns1(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 (since2^17 = 131,072 <= 200,000 < 262,144 = 2^18), exercising the widestnext_levellist. - Non-increasing node IDs (e.g.,
0 -> 2 -> 1in Example 2): Node IDs are only array indices, so following links from0works 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
RecursionErroron a deep chain of 200,000 nodes. - Counting edges instead of nodes: Initializing
depth = -1or only counting transitions between levels returns0for a single-node tree and3instead of4for Example 1. - Forgetting the empty-tree check: Starting unconditionally with
current_level = [0]raisesIndexErrorwhenchildrenis[]. - Forgetting
!= -1before indexingchildren: In Python,children[-1]does not raise an error — it reads the last element ofchildren! Appending-1intonext_levelsilently jumps to noden - 1and can cause an infinite loop. - Using
list.pop(0)in a single-queue BFS: Removing element0from a Pythonlistshifts every remaining element left inO(k)time, turning wide trees intoO(n^2)time; use two level lists as shown here orcollections.deque(a deque, or double-ended queue supportingO(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 awhileloop, updatebest_depth = max(best_depth, depth_so_far), and push any non--1child withdepth_so_far + 1. This also runs inO(n)time without recursion; its stack holds at mostO(h)entries for a tree of heighth(at mosth + 1on a skewed chain, andO(log n)on a balanced tree). - Single-queue BFS with
collections.deque: Store(node_id, node_depth)pairs or iteratefor _ in range(len(queue)):per level usingqueue.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 == -1andright_child == -1(a true leaf), immediately return the currentdepth. 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 (withvisited[0] = Trueinitially) before starting the loop. Whenever you see a child indexchild != -1, check whetherchildlies outside0 <= child < len(children)orvisited[child]is alreadyTrue: if so, either two parents sharechildor there is a cycle, so raise an error instead of looping forever. Once thewhileloop finishes, verifyall(visited)to confirm every node was reachable from root0. - 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 recordparent[child] = nodewhenever you appendchildtonext_level, while also savingdeepest_leaf = current_level[0]before advancingcurrent_level. Once the loop terminates,deepest_leafsits on the bottommost layer; walk backward viacur = parent[cur]untilcur == -1, collecting node IDs into a list, and reverse that list inO(n)total time andO(n)space.
Follow-up questions
- How would you modify the traversal to find the shortest root-to-leaf node count instead?
- How could you detect malformed inputs such as cycles, shared children, or unreachable nodes?
- How would you reconstruct the actual sequence of node IDs along a deepest root-to-leaf path?
Similar questions
- Indexed Word Distance Queries
- Largest Value from Concatenated Integers
- Non-Adjacent Flowerbed Placement
- Validate Plain Signed Decimal Strings
- Stack vs. Heap Memory
- Find Downstream Impacted Microservices
More LinkedIn interview questions
- Shortest-Path Robot Navigation on an Unmapped Grid Medium
- Key-Aligned Merge of Two Rooted N-ary Trees Easy
- Runner-Up Score in a Knockout Min-Tree Medium Pro
- Repeated Word Proximity Queries Hard Pro
- Zigzag Depth-Order Tree Traversal Medium Pro
- Non-Adjacent Flowerbed Placement Medium Pro
- Queue Pooling, Skewed Graphs, and Shrinkage Medium Pro
- Distributed Key-Value Store for Small-Team Internal Services Medium Pro
- Two-Project Architecture and Trade-Off Walkthrough Medium Pro
- Defending a Hard Architectural Trade-Off and Its Implementation Medium Pro