Maximum Depth of Binary Tree
A startup keeps its org chart as a binary tree: every employee is a node, and each node has at most two direct reports as its children. HR wants to know how many levels the chart spans.
Given the root of the tree, return the number of nodes on the longest path that starts at the root and keeps going down until it reaches a node with no children. An empty chart (root is null) has 0 levels.
Input: root = [10,4,15,2,null,null,20,1] Output: 4
Explanation: The chain 10 → 4 → 2 → 1 passes through four people. The other branch, 10 → 15 → 20, is one level shorter.
Input: root = [8,null,9,null,10] Output: 3
Explanation: Each person has a single report on the right, so the chart is a chain of three.
Input: root = [] Output: 0
Constraints
- The chart has at most 10^4 nodes.
- Node values are between -100 and 100.
💡 Hint 1
The depth of a tree is 1 + the larger depth of its two subtrees.
💡 Hint 2
An empty tree has depth 0.
Try it yourself first ✎
Solutions stick better after a real attempt. Peek when you're ready.
Approach
Recursive DFS: an empty node has depth 0; otherwise the depth is 1 + max(depth(left), depth(right)). An iterative BFS that counts levels works equally well and avoids deep recursion on skewed trees.
function maxDepth(root) {
if (!root) return 0;
return 1 + Math.max(maxDepth(root.left), 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));
}
}No submissions yet. Press Submit to run your code against every test.
/**
* Definition for a binary tree node (provided):
* function TreeNode(val, left, right) { this.val = val ?? 0; this.left = left ?? null; this.right = right ?? null; }
*
* @param {TreeNode} root
* @return {number}
*/
function maxDepth(root) {
}Run your code to see results here.