☰ All problems

Maximum Depth of Binary Tree

EasyTreeBinary TreeDFS

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.

Example 1
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.

Example 2
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.

Example 3
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.

/**
 * 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) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc