Maximum Depth of Binary Tree
Given the root
Example 1
Input: root = [3,9,20,null,null,15,7]
Output: 3
Output: 3
Example 2
Input: root = [1,null,2]
Output: 2
Output: 2
Constraints:
0 <= Number of nodes <= 104-100 <= Node.val <= 100
Solution 1: Recursive DFS
The depth of a tree is 1 + the maximum depth of its left and right subtrees. This leads to a clean one-line recursive solution.
Algorithm:
- Base case: if
, depth is 0.root == null - Recursively compute depth of left and right subtrees.
- Return
.1 + Math.max(leftDepth, rightDepth)
Java
public int maxDepth(TreeNode root) {
if (root == null) return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return 1 + Math.max(leftDepth, rightDepth);
}
Complexity:
- Time: O(n). Visits every node once.
- Space: O(h). Recursion stack depth equals tree height (O(log n) balanced, O(n) worst).
Solution 2: Iterative BFS (Level-Order)
Process the tree level by level with a queue. Each iteration of the outer loop represents one complete level: count the levels.
Java
public int maxDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int depth = 0;
while (!queue.isEmpty()) {
int levelSize = queue.size(); // nodes at current level
depth++;
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
return depth;
}
Complexity:
- Time: O(n). Every node is enqueued and dequeued exactly once.
- Space: O(n). At most n/2 nodes in the queue at the widest level.
Complexity Analysis
| Approach | Time | Space |
|---|---|---|
| Recursive DFS | O(n) | O(h): call stack |
| Iterative BFS | O(n) | O(n): queue |
Note: For this problem both approaches are O(n) time. DFS is preferred for its simplicity and O(h) space on balanced trees.