给定一棵多叉树,求出这棵树的直径,即树上最远两点的距离。
包含n个结点,n-1条边的连通图称为树。
示例1的树如下图所示。其中4到5之间的路径最长,是树的直径,距离为5+2+4=11
数据范围:
,保证最终结果满足
要求:空间复杂度:
,时间复杂度
6,[[0,1],[1,5],[1,2],[2,3],[2,4]],[3,4,2,1,5]
11
2,[[0,1],[1,2]],[1]
1
from collections import defaultdict class Solution: def solve(self , n: int, Tree_edge: List[Interval], Edge_value: List[int]) -> int: def dfs(node, parent, graph): max_distance = 0 max_node = node for neighbor, weight in graph[node]: if neighbor == parent: # 避免回到父节点 continue distance, cur_max_node = dfs(neighbor, node, graph) distance += weight if distance > max_distance: max_distance = distance max_node = cur_max_node return max_distance, max_node graph = defaultdict(list) for i in range(len(Tree_edge)): u, v, weight = Tree_edge[i].start, Tree_edge[i].end, Edge_value[i] graph[u].append((v, weight)) graph[v].append((u, weight)) # 第一次 DFS 从任意节点开始,找到最远的节点 start_node = Tree_edge[0].start _, max_node = dfs(start_node, None, graph) # 第二次 DFS 从找到的最远节点开始,计算直径 max_distance, _ = dfs(max_node, None, graph) return max_distance