#K39942. Tree Diameter
Tree Diameter
Tree Diameter
You are given an undirected tree with n nodes. A tree is an acyclic connected graph. The tree is provided in the form of edges. Your task is to compute the diameter of the tree. The diameter of a tree is defined as the number of edges in the longest path between any two nodes.
Note: The nodes are labeled from 0
to n-1
.
Example:
Input: 7 0 1 0 2 1 3 1 4 2 5 2 6</p>Output: 4
In the above tree, one of the longest paths is from node 3 to node 5 (or 3 to 6) via nodes 1, 0, and 2, which contains 4 edges.
inputFormat
The input is read from 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 integers
u
andv
, representing an undirected edge between nodesu
andv
.
It is guaranteed that the input forms a valid tree, and the nodes are numbered from 0
to n-1
.
outputFormat
Output to stdout a single integer — the diameter of the tree (i.e. the number of edges in the longest path between any two nodes).
## sample1
0