LeetCode 104: Maximum Depth of Binary Tree — Python Solution

LeetCode 104: Maximum Depth of Binary Tree is an Easy binary tree general problem. This Python walkthrough develops a recursive postorder solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyEasy
TopicBinary Tree General
Reusable patternrecursive postorder
ComplexityO(n) time and O(h) recursion space

Recognizing the pattern

Tree recursion works when the return value has one precise meaning for every subtree; the parent can then combine child results locally.

For this problem specifically, the depth of a node is one plus the larger depth of its children, with an empty subtree contributing zero. The invariant worth writing beside the code is: Each return value is the exact maximum root-to-leaf node count for that subtree.

Step-by-step algorithm

  1. Identify the input state consumed by maxDepth(root) and initialize the data required by the recursive postorder pattern.
  2. The depth of a node is one plus the larger depth of its children, with an empty subtree contributing zero.
  3. After each update, verify the page’s central invariant: Each return value is the exact maximum root-to-leaf node count for that subtree.
  4. Finish only after the boundary behavior is covered: An empty tree has depth zero; a skewed tree uses linear recursion depth.

Python solution

LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.

class Solution:
    def maxDepth(self, root):
        if not root:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

Reading the implementation

The main entry point is maxDepth(root). The implementation keeps little named state because each operation can be resolved directly from the current input position.

The entry point is recursive: each call reduces the remaining tree, graph, or search state before combining the returned information. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, the depth of a node is one plus the larger depth of its children, with an empty subtree contributing zero.

Correctness argument

Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.

Inductive step. The depth of a node is one plus the larger depth of its children, with an empty subtree contributing zero. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so each return value is the exact maximum root-to-leaf node count for that subtree.

Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.

Complexity and trade-offs

O(n) time and O(h) recursion space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

An explicit stack avoids recursion-depth limits, but it must carry the same state that recursive call frames provide automatically. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

root=tree([3,9,20,None,None,15,7]); assert Solution().maxDepth(root)==3

Common mistakes and edge cases

  • Problem-specific boundary: An empty tree has depth zero; a skewed tree uses linear recursion depth.
  • Pattern-level pitfall: Write the empty-subtree result first and keep returned subtree information separate from any global answer updated at a node.
  • Invariant check: after every update, confirm that each return value is the exact maximum root-to-leaf node count for that subtree.

Interview review checklist

  • Explain why recursive postorder matches the structure of this input.
  • State the invariant in one sentence before tracing code: Each return value is the exact maximum root-to-leaf node count for that subtree.
  • Derive O(n) time and O(h) recursion space from how many times each element or state is visited.
  • Test the boundary explicitly: An empty tree has depth zero; a skewed tree uses linear recursion depth.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 146. LRU Cache · Next: 100. Same Tree