12. Maximum Depth of Binary Tree
easyAsked at CanvaFind the maximum depth of a binary tree — Canva uses this to verify simple recursion sense around bounding deeply nested group depth.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree, return its maximum depth — the number of nodes along the longest path from the root to a leaf.
Constraints
0 <= nodes <= 10^4-100 <= Node.val <= 100
Examples
Example 1
root=[3,9,20,null,null,15,7]3Example 2
root=[1,null,2]2Approaches
1. BFS level count
Level-order traversal incrementing depth per level.
- Time
- O(n)
- Space
- O(n)
if (!root) return 0;
let depth = 0, q = [root];
while (q.length) {
const next = [];
for (const n of q) { if (n.left) next.push(n.left); if (n.right) next.push(n.right); }
q = next; depth++;
}
return depth;Tradeoff:
2. DFS recursion
Depth of any subtree = 1 + max(left, right). Short, classic.
- Time
- O(n)
- Space
- O(h)
function maxDepth(root) {
if (!root) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}Tradeoff:
Canva-specific tips
Canva interviewers like both recursive and iterative versions side by side — it shows you understand when call-stack depth could matter for huge designs.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Maximum Depth of Binary Tree and other Canva interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →