Skip to content
mlmentorship

Return one subtree height after both children

Combine child heights for a longest path, then change execution depth or count every node.

Published · 8 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Return one subtree height after both children

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. The root of a finite binary tree with val, left, and right fields. Output. Return the greatest number of nodes on any path from the root to a leaf. Rules. Count nodes, not edges. A leaf has depth one and an empty tree has depth zero. Assume no shared nodes or cycles. Leave node values and child links unchanged. Example. A root 3 has children 9 and 20; node 20 has children 15 and 7. Return 3, for either path 3 -> 20 -> 15 or 3 -> 20 -> 7. Its compact level-order notation is [3, 9, 20, null, null, 15, 7].

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Each recursive call returns the height of its subtree, so a parent needs only 1 + max(left height, right height).

Problem trace

Add the current node to the larger returned child depth

Input and goalFind the number of nodes on the longest root-to-leaf path.
Start the root callFor tree [3,9,20,null,null,15,7], call max_depth(3). The stack contains [3], and neither child height is known yet.
callStack[3]knownReturnsnone
node 3
call max_depth(3)
call stack
[3]
known returns
none

Recognize it
Use this pattern when a tree property for a node can be computed only after both child subtrees return summaries, especially height, diameter contributions, or root-to-leaf aggregates.
Keep true
Whenever max_depth(node) returns d, d is exactly the number of real nodes on the longest path from node to a leaf; max_depth(None) returns 0, making a leaf return 1.
Reuse it
Define the null identity first, ask each child for the smallest sufficient summary, and combine those summaries once; the same postorder fold supports subtree size, height, and path calculations.
For tree [3,9,20,null,null,15,7], call max_depth(3). The stack contains [3], and neither child height is known yet. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does the root return three when its child heights are one and two?
Full interview answer 8 min read

Measure the longest root-to-leaf path in a binary tree by counting its nodes.

Problem

Input. The root of a finite binary tree with val, left, and right fields.

Output. Return the greatest number of nodes on any path from the root to a leaf.

Rules. Count nodes, not edges. A leaf has depth one and an empty tree has depth zero. Assume no shared nodes or cycles. Leave node values and child links unchanged.

Example. A root 3 has children 9 and 20; node 20 has children 15 and 7. Return 3, for either path 3 -> 20 -> 15 or 3 -> 20 -> 7. Its compact level-order notation is [3, 9, 20, null, null, 15, 7].

Picture

Each child sends one number upward, not its whole path. Leaves 9, 15, and 7 each return 1. Node 20 combines 1 and 1 into 2; root 3 combines 1 and 2 into 3.

Problem trace

Separate returned heights: extend the longer child path

Worked example: add this node to the larger returned child depthChild depths 2 and 4 produce parent depth 5. Adding both child depths would count nodes from different root-to-leaf paths.The parent extends only the largerchild depthleft return2right return4max+1 node5One parent extends the longer childroute to five.
Read it this way: Child depths 2 and 4 produce parent depth 5. Adding both child depths would count nodes from different root-to-leaf paths. Why does adding two and four count nodes from two different root-to-leaf routes?
Reference drawing

Problem trace

Add the current node to the larger returned child depth

Worked example: add this node to the larger returned child depthChild depths 2 and 4 produce parent depth 5. Adding both child depths would count nodes from different root-to-leaf paths.The parent extends only the largerchild depthleft return2right return4max+1 node5One parent extends the longer childroute to five.
Execution trace
Input and goalFind the number of nodes on the longest root-to-leaf path.
Start the root callFor tree [3,9,20,null,null,15,7], call max_depth(3). The stack contains [3], and neither child height is known yet.
callStack[3]knownReturnsnone
node 3
call max_depth(3)
call stack
[3]
known returns
none

Recognize it
Use this pattern when a tree property for a node can be computed only after both child subtrees return summaries, especially height, diameter contributions, or root-to-leaf aggregates.
Keep true
Whenever max_depth(node) returns d, d is exactly the number of real nodes on the longest path from node to a leaf; max_depth(None) returns 0, making a leaf return 1.
Reuse it
Define the null identity first, ask each child for the smallest sufficient summary, and combine those summaries once; the same postorder fold supports subtree size, height, and path calculations.
For tree [3,9,20,null,null,15,7], call max_depth(3). The stack contains [3], and neither child height is known yet. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does the root return three when its child heights are one and two?
Read it this way: Child depths 2 and 4 produce parent depth 5. Adding both child depths would count nodes from different root-to-leaf paths. Why does adding two and four count nodes from two different root-to-leaf routes?

Every path through a real node uses that node, then at most one child path. Therefore its node-count height is:

The returned number is the exact height of that subtree. Node values do not enter the recurrence.

Code

def max_depth(root: TreeNode | None) -> int:
   if root is None:
      return 0
   return 1 + max(max_depth(root.left), max_depth(root.right))

Each node is visited once: time and recursive stack space. A chain has , not . Python can raise RecursionError on a deep tree before the mathematical computation finishes.

Failure Check

Counting edges changes the convention: the source tree has two edges on its longest path, but three nodes. Using addition instead of max answers a different question: it returns 5 for this tree.

Change the Execution

New task: Trees can exceed Python’s recursive call limit.

Picture and change: Carry (node, depth) work items explicitly. best is the greatest depth among nodes already removed from the stack.

def max_depth_iterative(root):
   stack = [] if root is None else [(root, 1)]
   best = 0
   while stack:
      node, depth = stack.pop()
      best = max(best, depth)
      if node.left is not None:
         stack.append((node.left, depth + 1))
      if node.right is not None:
         stack.append((node.right, depth + 1))
   return best

Check: The source tree still returns 3; an empty tree returns 0. This uses time and auxiliary space on a binary tree. It removes recursive calls, not memory needs or the no-cycle assumption.

Use when: Execution depth changes but the requested height does not.

Change the Aggregate

New task: Count every node, not one longest path.

Picture and change: Both child contributions now matter, so replace max with addition. The returned fact becomes subtree size.

def tree_size(root):
   if root is None:
      return 0
   return 1 + tree_size(root.left) + tree_size(root.right)

Check: The source tree has size 5 and height 3. Empty and singleton trees have sizes 0 and 1. Time remains , with recursive stack space and the same recursion limit.

Use when: All descendants contribute to the result.

Transfer Check

Why does the parent not need the actual longest path?

Answer

The output requests only a length. The larger child height contains everything needed for that scalar result. Returning the path itself would require a different summary.

Compare level-order traversal when the task requires whole levels rather than one returned height.