Practice: Maximum Depth of Binary Tree

Problem: https://leetcode.com/problems/maximum-depth-of-binary-tree/

Recognition reminder: “how deep is this tree” is the cleanest return-only DFS in the course. The value each recursive call hands back is the answer for its subtree; there is nothing to record on the side. Internalize this one as the baseline against which the canonical’s return-versus-record split stands out.

Before you start (the five-beat rhythm)

  1. Your Pattern Card for this week is already written.
  2. Name the pattern aloud and write your approach as a plain-English comment before any code.
  3. Struggle floor: 25 minutes unaided. No hints, no AI, no Discuss tab.
  4. If stuck past the floor, ask the tutor for a hint. Six rungs, one per ask.
  5. Debrief in your commit message before moving to the next problem.

Your target

Fill these in yourself before you look at anyone else’s solution:

Target time complexity:  ____
Target space complexity: ____

You touch every node once. The space question is about the recursion stack: how deep does it go, and how does that differ between a balanced tree and a skewed one? Name what dominates, and which tree shape is the worst case for space.

The shape of the input and the output

You implement a function max_depth(root) -> int. The argument root is a TreeNode (with val, left, right) or None. The depth is the number of nodes along the longest path from the root down to a leaf. The empty tree None has depth 0; a single node has depth 1; the tree [3, 9, 20, null, null, 15, 7] has depth 3.

The base case is the lesson: an empty subtree (None) has depth 0, and a node’s depth is 1 plus the larger of its two children’s depths. Recurse into None; do not special-case leaves. Optionally, solve it a second way with a BFS level count and confirm the two agree; that connects this problem to the level-order traversal next door.

Where your code goes

Write your solution as a function max_depth(root) in a file named solution.py in your own work repo (see getting-started.md), not in the course repo. Define your own TreeNode class (the same three-attribute shape the test uses). This folder ships only the problem spec and a provided-example test (tests/test_provided.py) so you can check the given cases locally before you submit to LeetCode’s judge. The test builds real trees for you from level-order lists. The judge is the oracle; the tutor will not confirm your answer by reading it.

Debrief (paste into your commit message)

1. What pattern did this turn out to be?
2. What was the trigger phrase or input shape that should have made me reach for it?
3. What was the time and space complexity, and what would dominate at scale?
4. What edge case would have broken my first attempt?
5. What would I do differently in three days when I see this cold?