Python coding

Depth of the deepest leaf

Write max_depth(root): given the root of a binary tree, return how many nodes lie on the longest path from the root down to a leaf. An empty tree (None) has depth 0 and a single node has depth 1. Each TreeNode has val, left and right.

The tests call the provided run_max_depth(values), where values lists the tree level by level with null for a missing child: [1, null, 2, 3] is a root 1 with only a right child 2, whose left child is 3.

  • run_max_depth([8,3,10,null,6,9]) → 3
  • run_max_depth([1,null,2,3]) → 3
  • run_max_depth([]) → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Think recursively: if you already knew the depth of the left and right subtrees, what would the depth of the whole tree be?

Hint 2

1 + max(left, right), with 0 for a missing subtree. Returning 0 for None covers the empty tree and nodes with one child with no extra cases.

Solution and why it works
pythonO(n) · O(h), h = height (recursion stack)
# --- your 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))


# --- provided: do not edit ---
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def build_tree(values: list[int | None]) -> TreeNode | None:
    # Level order: each existing node takes the next two entries as its left and right child.
    nodes = [None if v is None else TreeNode(v) for v in values]
    children = iter(nodes[1:])
    for node in nodes:
        if node is not None:
            node.left = next(children, None)
            node.right = next(children, None)
    return nodes[0] if nodes else None


def run_max_depth(values: list[int | None]) -> int:
    return max_depth(build_tree(values))

A tree is one level deeper than its deeper subtree, and an empty subtree adds nothing: 1 + max(left, right) with 0 for None. Every node is visited once, so time is O(n); the recursion stack holds one call per level, O(h), which reaches O(n) when the tree is a single chain. The trap is the base case: put it at None, returning 0. Stopping at leaves instead needs extra checks for nodes with one child, and returning -1 counts edges, not nodes.