#K74407. Longest Path in a Tree

    ID: 34190 Type: Default 1000ms 256MiB

Longest Path in a Tree

Longest Path in a Tree

Given a tree with n nodes, your task is to find the length of the longest path in the tree, also known as the diameter. The tree is an undirected, acyclic connected graph. The diameter is defined as the maximum number of edges found in any path between two nodes in the tree.

An efficient way to solve this problem is to perform two breadth-first searches (BFS):
1. Start a BFS from an arbitrary node to find the farthest node from it.
2. Then start a second BFS from this farthest node to determine the maximum distance, which is the diameter.

Note: If the tree has only one node, then the longest path length is 0.

inputFormat

The first line contains an integer n, the number of nodes in the tree. Each of the next n - 1 lines contains two integers u and v, representing an undirected edge between nodes u and v.

outputFormat

Output a single integer which is the length of the longest path (diameter) of the tree.## sample

5
1 2
1 3
3 4
3 5
3