How Deep the Cave Goes

Easydepth-first searchAlso known as Maximum Depth of Binary Tree

A caving club has mapped a cave as a binary tree: from each chamber at most two tunnels lead further down, and tunnels never rejoin. Each chamber has a number painted on the wall. To know how many rope anchors to pack, the club needs the number of chambers on the longest descent, counting the entrance and the last chamber.

Your task

Write caveDepth(root). Return the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0, and a tree with only a root has depth 1.

Trees are shown in level order, like [1, 2, 3, null, 4], where null marks a missing child. Your function receives real TreeNode objects with val, left and right.

caveDepth(root: TreeNode) → int

Examples

Example 1
Input
root = [1, 2, 3, null, 4, 5, null, null, null, 6]
Output
4
Why

The left descent 1 → 2 → 4 passes through 3 chambers, and the right one, 1 → 3 → 5 → 6, passes through 4. Following only the left tunnels would wrongly give 3.

Example 2
Input
root = [8]
Output
1
Why

The cave is only the entrance. The answer counts chambers and not tunnels, so it is 1 and not 0.

Constraints

  • 0 ≤ number of chambers ≤ 1,000
  • -1,000 ≤ chamber number ≤ 1,000
  • The tree is at most 500 levels deep.
Start with brute force

List every route from the entrance to a dead end and keep the longest. Storing the routes means copying paths over and over, and a chain of 1,000 chambers makes routes up to 1,000 long. You only need lengths, and each chamber can compute its depth from its children's answers in a single visit.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code