Longest Handoff Chain

Medium · Trees & BSTs · about 20 min

In a company org chart (a binary tree), a message can be handed between a person and their manager or direct report, one hop at a time, never visiting anyone twice. The tree is a level-order list: the root first, then each node's left and right child in turn, with None (Python) / null (JavaScript) for a missing child. A build(level) helper in the starter turns it into nodes with .val, .left and .right.

Return the number of hops (edges) on the longest possible handoff chain between any two people. The chain does not have to pass through the top person. An empty chart or a chart of one person gives 0.

  • Up to 10,000 people, values are any integers.

Examples:

longest_handoff([1, 2, 3, 4, 5]) → 3 (4 → 2 → 1 → 3, or 5 → 2 → 1 → 3)

longest_handoff([1, 2]) → 1

Hints

  • Picture the highest person on the best chain. How long can the chain be on each side of them?
  • Compute each subtree's height once, bottom-up, and use it at the parent.
  • Track the best over every node, not only at the root, and count edges, not people.

Learn the pattern first: the Trees & BSTs lesson.

More Trees & BSTs problems