45. Maximum Depth of Binary Tree
Return the maximum depth of a binary tree: the number of nodes on the longest path from the root down to a leaf.
Trees are given in level order, with null for a missing child.
Example 1
Input:
root = [3,9,20,null,null,15,7]Output:
3Example 2
Input:
root = [1,null,2]Output:
2Hint 1
Depth of a node = 1 + the larger depth of its two subtrees.
Approach 1: Recursive DFS
Post-order: combine the children’s answers.
⏱ Time O(n)💾 Space O(h)
Approach 2: BFS by levels ✅
Count how many levels a queue processes.
⏱ Time O(n)💾 Space O(w)
Reference solution for BFS by levels (time O(n), space O(w)). Each solution passes every test in all four languages.
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};function maxDepth(root) {
if (!root) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
Watch the core idea of this problem step by step. Change the input and press Visualize.
Explained in the lesson Binary Trees & BSTs.
Run your code to see results here.