1245. Tree Diameter

Given an undirected tree, return its diameter: the number of edges in a longest path in that tree.

The tree is given as an array of  edges  where edges[i] = [u, v] is a bidirectional edge between nodes  u and v .  Each node has labels in the set {0, 1, ..., edges.length} .

 

Example 1:

Input:

 edges = [[0,1],[0,2]]
Output:

 2
Explanation: 

A longest path of the tree is the path 1 - 0 - 2.

Example 2:

Input:

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

 4
Explanation: 

A longest path of the tree is the path 3 - 2 - 1 - 4 - 5.

 

Constraints:

1、题目描述

给你这棵「无向树」,请你测算并返回它的「直径」:这棵树上最长简单路径的 边数。

我们用一个由所有「边」组成的数组 edges 来表示一棵无向树,其中 edges[i] = [u, v] 表示节点 uv 之间的双向边。

树上的节点都已经用 {0, 1, ..., edges.length} 中的数做了标记,每个节点上的标记都是独一无二的。

示例 1:

img

输入:edges = [[0,1],[0,2]]
输出:2
解释:
这棵树上最长的路径是 1 - 0 - 2,边数为 2。

示例 2:

img

输入:edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]
输出:4
解释: 
这棵树上最长的路径是 3 - 2 - 1 - 4 - 5,边数为 4。

提示:

Difficulty:

Medium

Lock:

Prime

Company:

Facebook Google

Solution(Chinese):

LEETCODE 1245. Tree Diameter 解题思路分析