All problems

Problem 180

Tree Diameter

Medium · 20 pts · Tree, Graph, Depth-First Search

Problem

You are given a tree with N nodes (a connected undirected graph with N - 1 edges and no cycles). Print its diameter: the number of edges on the longest path between any two nodes. A tree with a single node has diameter 0. A classic trick uses two searches. Run BFS from any node and find the farthest node A. Then run BFS from A; the distance to the farthest node from A is the diameter.

Input

First line: integer N. Next N - 1 lines: an edge u v.

Output

Print the diameter.

Constraints

1 <= N <= 100000

Example input

5
1 2
1 3
2 4
3 5

Example output

4

Explanation

Node 1 is connected to 2 and 3, node 2 to 4, and node 3 to 5. The longest path is 4 - 2 - 1 - 3 - 5, which uses 4 edges, so the diameter is 4.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Max Area of Island Next: House Robber