Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Input: root = [3,9,20,null,null,15,7]
Output: 3
Tree:
3
/ \
9 20
/ \
15 7
Depth: Root (3) has depth 1, nodes (9, 20) have depth 2,
nodes (15, 7) have depth 3
Input: root = [1,null,2]
Output: 2
Tree:
1
\
2
Input: root = []
Output: 0
The depth of a tree is determined by its tallest subtree + 1 (for the root).
Think recursively:
This naturally fits a post-order DFS traversal where we calculate subtree depths before using them.
This is a Tree Recursion problem with:
Why this works:
Use level-order traversal:
Time: O(n) where n = number of nodes
Space: O(h) where h = height of tree
1class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode() {}
6 TreeNode(int val) { this.val = val; }
7 TreeNode(int val, TreeNode left, TreeNode right) {
8 this.val = val;
9 this.left = left;
10 this.right = right;
11 }
12}
13
14class Solution {
15 public int maxDepth(TreeNode root) {
16 // Base case: null node has depth 0
17 if (root == null) {
18 return 0;
19 }
20
21 // Recursively calculate depth of left and right subtrees
22 int leftDepth = maxDepth(root.left);
23 int rightDepth = maxDepth(root.right);
24
25 // Current depth = 1 (this node) + max of subtree depths
26 return 1 + Math.max(leftDepth, rightDepth);
27 }
28}
29