forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1245.go
More file actions
37 lines (34 loc) · 690 Bytes
/
Copy path1245.go
File metadata and controls
37 lines (34 loc) · 690 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
var g map[int][]int
var res int
func treeDiameter(edges [][]int) int {
res = 0
g = make(map[int][]int)
for _, it := range edges {
g[it[0]] = append(g[it[0]], it[1])
g[it[1]] = append(g[it[1]], it[0])
}
dfs(0, -1)
return res
}
func dfs(cur, pre int) int {
d1, d2 := 0, 0
for _, i := range g[cur] {
if i != pre {
d := dfs(i, cur)
if d > d1 {
tmp := d1
d1, d2 = d, tmp
} else if d > d2 {
d2 = d
}
}
}
res = max(res, d1 + d2)
return d1 + 1
}
func max(a, b int) int {
if a > b {
return a
}
return b
}