Maximum Depth of Binary Tree

EasyTrees

Given the root of a binary tree, return its depth: the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0.

On this page a tree is written in level order, top to bottom and left to right, with null where a child is missing: [6, 3, 8, 1] is 6 with children 3 and 8, and 3 with a left child 1.

Examples

Example 1
Input:  root = [4, 2, 7, null, null, 5, 9, null, 6]
Output: 4

The longest path is 4 → 7 → 5 → 6, four nodes.

Example 2
Input:  root = [3, null, 8]
Output: 2

The root and its one child, 8, on the right.

Constraints

  • The tree has 0 to 10⁴ nodes.
  • -100 ≤ node.val ≤ 100

Stuck?

Hint 1

A tree is one level deeper than the deeper of its two subtrees.

Hint 2

Recurse, with an empty tree as the base case at depth 0. Or count the levels with a queue, one level at a time.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur