104. Maximum Depth of Binary Tree
At a Glance
- Topic: trees
- Pattern: Tree DFS
- Difficulty: Easy
- Companies: Amazon, Google, Meta, Apple, Bloomberg
- Frequency: Very High
- LeetCode: 104
Problem (one-liner)
Given the root of a binary tree, return the number of nodes along the longest path from the root down to a leaf (depth as edge count is often “levels − 1”; here LeetCode uses node count depth = root-to-leaf nodes).
Recognition Cues
- "Maximum depth" / "height" of the tree
- Longest path root to any leaf
- Often first introductory recursion on trees
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force —
O(n)time /O(n)space — collect all root-to-leaf paths and take max length (overkill). - Better —
O(n)time /O(n)space — BFS level counting (same asymptotic, queue memory). - Optimal —
O(n)time /O(h)stack — DFS: depth =1 + max(depth(left), depth(right)).
Optimal Solution
Go
package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
leftDepth := maxDepth(root.Left)
rightDepth := maxDepth(root.Right)
if leftDepth > rightDepth {
return 1 + leftDepth
}
return 1 + rightDepth
}JavaScript
class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function maxDepth(root) {
if (root === null) {
return 0;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}Walkthrough
Tree: 3 / 9,20 / null,null,15,7
| node | left depth | right depth | return |
|---|---|---|---|
9 | 0 | 0 | 1 |
15 | 0 | 0 | 1 |
7 | 0 | 0 | 1 |
20 | 1 | 1 | 2 |
3 | 1 | 2 | 3 |
Invariant: subtree depth is correctly computed bottom-up; empty subtree contributes 0.
Edge Cases
root == null→ depth0- Single node → depth
1 - Skewed list → depth
n
Pitfalls
- Off-by-one: returning depth without
+1for current level - Confusing edge-based height with node-based depth (stay consistent with problem definition)
Similar Problems
- 226. Invert Binary Tree — same traversal shell, different combine step.
- 110. Balanced Binary Tree — uses subtree heights for balance, not just max.
- 543. Diameter of Binary Tree — depth used to update a global best path length.
Variants
- Minimum depth to leaf → different combine (careful: not just
minof children if one side null). - Binary tree max width by level → BFS with level sizes.
Mind-Map Tags
#trees #dfs #height #recursion #divide-and-conquer-on-tree
Last updated on
Spotted something unclear or wrong on this page?