← Back to DSA
#104
Maximum Depth of Binary Tree
Maximum Depth of Binary Tree solution for LeetCode 104, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Maximum Depth of Binary Tree
Why it belongs on this sheet
This is the easiest tree recurrence and the fastest way to warm up before deeper tree questions.
Pattern
Height from children
Approach
The depth of a tree is 1 + max(left depth, right depth). Use recursion and return 0 for a null node.
Java solution
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
Complexity
- Time:
O(n) - Space:
O(h)recursion stack
Interview note
Say what the function returns for each node before writing code. That keeps recursion grounded.
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)