How Deep the Cave Goes

Easydepth-first searchAlso known as Maximum Depth of Binary Tree

A caving club has mapped a cave. From the entrance chamber, at most two tunnels lead further down, and the same is true in every chamber below. Tunnels never join up again, so the map is a binary tree. Each chamber has a number painted on the wall.

Before the next trip, the club needs to know how many chambers the longest descent passes through, counting the entrance and the last chamber. That decides how many rope anchors to pack.

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

From the entrance 1, the left tunnel goes 1 → 2 → 4 (3 chambers). The right tunnel goes 1 → 3 → 5 → 6 (4 chambers). The deepest descent passes 4 chambers. Following only the left tunnels would wrongly give 3.

Example 2
Input
root = [8]
Output
1
Why

A cave with just the entrance chamber. The answer counts chambers, not tunnels, so it is 1, 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, count the chambers on each, and keep the largest count.

That works, but if you store each route as you go you copy paths over and over: a cave with 1,000 chambers in a long chain makes routes of up to 1,000 chambers each. You do not need the routes at all, only their lengths, and each chamber can compute its own depth from its children's answers in one 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