316. Tree Diameter

There is an undirected tree of n nodes labeled from 0 to n - 1. You are given a 2D array edges where edges.length == n - 1 and edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the tree.

Return the diameter of the tree.

The diameter of a tree is the longest path between any two nodes in the tree.

Example 1:

Input: edges = [[0,1],[1,2],[2,3]]

Output: 3

Explanation:

The longest path is from node 0 -> 1 -> 2 -> 3, with length 3.

Example 2:

Input: edges = [[0,1],[0,2],[1,3],[1,4],[4,5]]

Output: 4

Explanation:

The longest path is 2 -> 0 -> 1 -> 4 -> 5, with length 4.

Now Your Turn!

Pick the correct output for the given input

Input: edges = [[0,1],[1,2],[2,3],[3,4]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • n == edges.length + 1
  • 1 <= n <= 104
  • 0 <= ai, bi < n
  • ai != bi

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int treeDiameter(vector<vector<int>>& edges) {
//Your Code Goes Here
}
};
Test Case

Input:

Edges