Longest Museum Stroll

Mediumdepth-first searchAlso known as Diameter of Binary Tree

A small museum is a maze of rooms joined by doorways. From the entrance hall, at most two doorways lead to further rooms, and each of those rooms leads to at most two more. There are no loops, so the floor plan is a binary tree with the entrance hall at the root. Each room has a number.

A fitness app wants to advertise the museum's longest stroll: the longest walk between any two rooms that never goes through the same doorway twice. The walk does not have to start at the entrance, and it may go up toward the entrance and back down a different branch.

Your task

Write longestStroll(root). Return the number of edges (doorways) on the longest path between any two nodes of the tree. The path does not need to pass through the root.

An empty tree and a tree with one node both return 0. Trees are shown in level order, like [1, 2, 3], where null marks a missing child. Your function receives real TreeNode objects with val, left and right.

longestStroll(root: TreeNode) → int

Examples

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

The longest stroll is 7 → 5 → 3 → 1 → 4 → 6: five doorways. It turns around at room 1 and never visits the entrance hall 2. A stroll from the entrance can only reach 4 doorways (2 → 1 → 3 → 5 → 7).

Example 2
Input
root = [1, 2, 3]
Output
2
Why

Walk 2 → 1 → 3. That visits 3 rooms but passes only 2 doorways, and the answer counts doorways.

Constraints

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

For every room, run a search to find the farthest room from it, and keep the largest distance found. Or, for every room, compute the depth of its two subtrees from scratch and add them.

Both are O(n²): each of up to 1,000 rooms starts a walk that can touch all 1,000 rooms. The repeated work is the subtree depths. A room's depth is needed by its parent too, so compute each depth once, bottom-up, and check the turning point while you are there.

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