Notes & software courses · Free to learn
Aph's Blog

LC104 Maximum Depth of Binary Tree 🟢

👋 อ่านฟรีทั้งหมดบน Aph's Blog — เนื้อหาภาษาไทย ทำตามทีละหน้าใน sidebar ได้เลย หากมีข้อเสนอแนะหรืออยากให้เพิ่มหัวข้อไหน บอกได้เสมอ

The opener for tree DFS — postorder: let both children report depth, then take 1 + max.

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1
Input:
root = [3,9,20,null,null,15,7]
Output:
3
Explanation:
The longest paths are 3 → 20 → 15 and 3 → 20 → 7 — each has 3 nodes.
Example 2
Input:
root = [1,null,2]
Output:
2
Explanation:
The longest path is 1 → 2 — 2 nodes.
Example 3
Input:
root = []
Output:
0
Explanation:
Empty tree — depth is 0.
Constraints (ข้อจำกัด)
  • The number of nodes is in the range [0, 10^4].
  • -100 <= Node.val <= 100
Full solution · Try yourself firstพับไว้ด้านใน — คลิกเมื่อพร้อมดู

This matches the "bottom-up combine" pattern — both children report depth first, then you summarize at the current node.

1. Mindset Shift

The naive way walks every root-to-leaf path and takes the longest — correct, but awkward to code.

Key insight: depth(tree) = 1 + max(depth(left), depth(right)). Let the children compute their own depths (postorder), then combine.

2. The Logic — 4 Steps

  1. Base case — if node is None → return 0
  2. Ask left — left = maxDepth(node.left)
  3. Ask right — right = maxDepth(node.right)
  4. Combine — return 1 + max(left, right)

3. LeetCode-Ready Code

Submit this on LeetCodepython
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        left = self.maxDepth(root.left)
        right = self.maxDepth(root.right)
        return 1 + max(left, right)

4. Dry Run — [3,9,20,null,null,15,7]

Call at nodeleftrightreturns
9 (leaf)001
15 (leaf)001
7 (leaf)001
201 (from 15)1 (from 7)2
3 (root)1 (from 9)2 (from 20)3

5. Edge Cases & Pitfalls

  • Forgetting the None base case → AttributeError on .left/.right
  • Count nodes, not edges — always add 1 for the current node

6. Time & Space Complexity

  • Time O(n) — visit every node once
  • Space O(h) — call-stack depth equals tree height (worst case h = n)
💡 Pattern summary

Tree postorder: children return answers first, then the current node combines them (here 1 + max) — a template for many tree problems.