LC104 Maximum Depth of Binary Tree 🟢
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.
- 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.
- Input:
- root = [1,null,2]
- Output:
- 2
- Explanation:
- The longest path is 1 → 2 — 2 nodes.
- Input:
- root = []
- Output:
- 0
- Explanation:
- Empty tree — depth is 0.
- 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
- Base case — if node is None → return 0
- Ask left — left = maxDepth(node.left)
- Ask right — right = maxDepth(node.right)
- Combine — return 1 + max(left, right)
3. LeetCode-Ready Code
# 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 node | left | right | returns |
|---|---|---|---|
| 9 (leaf) | 0 | 0 | 1 |
| 15 (leaf) | 0 | 0 | 1 |
| 7 (leaf) | 0 | 0 | 1 |
| 20 | 1 (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)
Tree postorder: children return answers first, then the current node combines them (here 1 + max) — a template for many tree problems.