求出这棵树的直径,即两个节点距离的最大值。
思路:求最大与次大
import collections
class Solution:
ans=0
def solve(self , n , es, ev):
g=collections.defaultdict(list)
for e,v in zip(es,ev):
g[e.start].append((e.end, v))
g[e.end].append((e.start, v))
def dfs(u,vis):
vis[u]=1
fir=sec=0
for v,w in g[u]:
if vis[v]: continue
w+=dfs(v,vis)
if w>fir: sec,fir=fir,w
elif w>sec: sec=w
self.ans=max(self.ans, fir+sec)
return max(fir,sec)
dfs(0,[False]*n)
return self.ans