Maximum Depth of Binary Tree
Difficulty: Easy · Pattern: Trees & BST · LeetCode #104
Return the maximum depth of a binary tree: the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0.
Examples
text
[8, 3, 10, 1, 6, null, 14] → 3
[1, null, 2, null, 3] → 3 (a chain)
[] → 0Hints
- The depth of a tree is 1 + the deeper of its two subtrees.
- Base case: an empty subtree has depth 0.
- Iteratively: BFS and count levels.
Approach
Recursive post-order: depth(node) = 0 if node is null, else 1 + max(depth(left), depth(right)). Each node is visited once. For extremely deep (skewed) trees, use iterative BFS to avoid recursion limits.
Complexity
Time: O(n). Space: O(h) recursion, where h is the height (O(n) worst case).
Python solution
def maxDepth(root):
if not root:
return 0
return 1 + max(maxDepth(root.left), maxDepth(root.right))JavaScript solution
function maxDepth(root) {
if (!root) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}