Tree Diameter

MediumGraphsbfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

An undirected tree has n nodes labeled 0 to n - 1. You are given its edges as edges, where edges[i] = [u, v] connects nodes u and v; there are exactly n - 1 edges, so n = edges.length + 1. Return the diameter of the tree: the number of edges on the longest simple path between any two nodes. A tree with a single node (no edges) has diameter 0.

Examples

Input: edges = [[0,1],[0,2]]
Output: 2
The longest path is `1 - 0 - 2`.
Input: edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]
Output: 4
The longest path is `3 - 2 - 1 - 4 - 5`.

Constraints

  • 0 <= edges.length < 10^4
  • edges[i].length == 2 and 0 <= u, v <= edges.length
  • u != v, and the edges form a single tree

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bfs problems