Maximum Depth of Binary Tree
Problem Statement:β
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.
Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 3
-
Example:
β Solution 1: Recursive Depth-First Search (DFS)β
class Solution {
public:
int solve(TreeNode *root){
if(root == NULL) return 0;
return 1 + max(solve(root->left), solve(root->right));
}
int maxDepth(TreeNode* root) {
return solve(root);
}
};
β Solution 2: Iterative Level Order Traversal (BFS)β
class Solution {
public:
int solve(TreeNode *root){
if(root == NULL) return 0;
queue<TreeNode*> qu;
qu.push(root);
int level = 0;
while(!qu.empty()){
int size = qu.size();
level++;
for(int i = 0; i < size; i++){
TreeNode* node = qu.front();
qu.pop();
if(node->left) qu.push(node->left);
if(node->right) qu.push(node->right);
}
}
return level;
}
int maxDepth(TreeNode* root) {
return solve(root);
}
};
π How It Worksβ
Recursive (DFS):β
- Postorder-style traversal.
- At each node, you ask for the depth of the left and right subtrees.
- Return
1 + max(left, right)as the depth of the current node. - Base case: if
root == NULL, return 0.
Iterative (BFS):β
- Performs level order traversal using a queue.
- Counts the number of levels visited.
- For each level, process all nodes and enqueue their children.
- The total number of levels visited is the depth.
π§© Key Formulaβ
Depth = 1 + max(depth(left), depth(right))
β±οΈ Time & Space Complexityβ
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Recursive DFS | O(n) | O(h) β height of tree (stack space) |
| Iterative BFS | O(n) | O(w) β max width (queue size) |
n= total nodesh= heightw= width of the widest level
β οΈ Edge Casesβ
- β
Empty tree β returns
0 - β
Only one node β returns
1 - β Left- or right-skewed tree β works for both DFS and BFS
π‘ Other Approachesβ
| Approach | Notes |
|---|---|
| Top-down DFS | Pass current depth as parameter and track max |
| DFS with global variable | Update max depth during traversal (less clean) |
π Related Problemsβ
- LeetCode 104. Maximum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- LeetCode 110. Balanced Binary Tree
- LeetCode 543. Diameter of Binary Tree
π¬