Longest Museum Stroll

Mediumdepth-first searchAlso known as Diameter of Binary Tree

A small museum is a maze of numbered rooms. From each room, at most two doorways lead further in, and there are no loops, so the floor plan is a binary tree with the entrance hall at the root.

A fitness app wants the museum's longest stroll: the longest walk between any two rooms that never uses a doorway twice. It need not start at the entrance, and it may go up toward the entrance and back down another branch.

Your task

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

An empty tree and a one-node tree both return 0. Trees are shown in level order, like [1, 2, 3], with null for 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 at room 1 and never visits the entrance hall 2. From the entrance you reach at most 4 doorways (2 → 1 → 3 → 5 → 7).

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

2 → 1 → 3 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, search for the farthest room from it, or recompute both subtree depths 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. The repeated work is the subtree depths. Compute each 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