#C2301. Finding the Tree Diameter

    ID: 45603 Type: Default 1000ms 256MiB

Finding the Tree Diameter

Finding the Tree Diameter

Given a tree with \( n \) nodes (numbered from 1 to \( n \)) and \( n-1 \) edges, your task is to compute the diameter of the tree. The diameter is defined as the number of edges in the longest path between any two nodes in the tree.

You can solve this problem by performing two breadth-first search (BFS) traversals. First, start from an arbitrary node (for example 1) to find the farthest node \( u \). Then, perform a second BFS starting from \( u \) to find the farthest node from \( u \) and record the distance. This distance is the tree's diameter.

The mathematical definition is given by:

\( \text{diameter} = \max_{u,v \in T} \text{dist}(u,v) \)

inputFormat

The input is provided via standard input (stdin) and has the following format:

  • The first line contains an integer \( n \), the number of nodes in the tree.
  • The next \( n-1 \) lines each contain two space-separated integers \( u \) and \( v \), representing an edge between nodes \( u \) and \( v \).

outputFormat

Output a single integer to standard output (stdout) which is the diameter of the tree (i.e., the longest distance between any two nodes).

## sample
5
1 2
1 3
2 4
2 5
3