Maximum Depth of Binary Tree
Easy · Trees
Jump to codeFind the number of nodes on the longest path from a binary tree’s root down to a leaf. An empty tree has depth zero.
Examples
Example 1
root = [3,9,20,null,null,15,7]
Output: 3
Example 2
root = [1,null,2]
Output: 2
Constraints
- 0 <= The number of nodes in the tree <= 100
- -100 <= Node.val <= 100
Function contract
Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.
Need a hint?
A node adds one level above its deepest child.
Asked in real interviews
Candidates reported versions of Maximum Depth of Binary Tree from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Return zero for null. Otherwise return 1 + max(depth(left), depth(right)). This definition works unchanged for a leaf because both child depths are zero. In a very skewed tree, consider an explicit stack to avoid recursion limits.
Complexity
O(n) time and O(h) stack space.
Python reference solution
def maxDepth(root):
if root is None:
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));
}
Java solution
import java.util.*;
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 6 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
3,
9,
20,
null,
null,
15,
7
]
]3
[
[
1,
null,
2
]
]2
[ [] ]
0
[
[
1
]
]1
[
[
1,
2,
null,
3
]
]3
Drafts are saved per language in this browser when storage is available.