-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathtreeDiameter.py
More file actions
40 lines (28 loc) · 794 Bytes
/
treeDiameter.py
File metadata and controls
40 lines (28 loc) · 794 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
38
39
40
from collections import deque
def treeDiameter(n, tree):
if len(tree) < 2:
return len(tree)
edges = {}
def add_edges(x, y):
if x in edges:
edges[x].append(y)
else:
edges[x] = [y]
for a, b in tree:
add_edges(a, b)
add_edges(b, a)
def find_farthest(f):
queue = deque([(f, 0)])
seen = set()
while queue:
at, dist = queue.popleft()
for t in edges.get(at):
if t in seen:
continue
else:
queue.append((t, dist+1))
seen.add(t)
return at, dist
point_1, _ = find_farthest(0)
_, answer = find_farthest(point_1)
return answer