Maximum Depth of Binary Tree
Difficulty: Easy
Problem
Given the root of a binary tree, return its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example
Input: root = [3,9,20,null,null,15,7]
Output: 3
Explanation: The tree has depth 3: The longest path is root(3) → 20 → 15 (or 7), which has 3 nodes.
Brute-force approach
Optimal approach
Key insight: The depth of any node = 1 + max(depth of left child, depth of right child). For null nodes, return 0.
Use recursive DFS to calculate depth. For each node, the depth equals 1 (for the current node) plus the maximum depth of its left and right subtrees.
Steps
- Base case: If node is null, return 0
- Recursively get the depth of the left subtree
- Recursively get the depth of the right subtree
- Return 1 + max(leftDepth, rightDepth)
Time complexity: O(n) · Space complexity: O(h)