Skip to content

Commit 933bb23

Browse files
authored
Create Find Minimum Diameter After Merging Two Trees.py
1 parent 55db568 commit 933bb23

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
'''
2+
There exist two undirected trees with n and m nodes, numbered from 0 to n - 1 and from 0 to m - 1, respectively. You are given two 2D integer arrays edges1 and edges2 of lengths n - 1 and m - 1, respectively, where edges1[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the first tree and edges2[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the second tree.
3+
4+
You must connect one node from the first tree with another node from the second tree with an edge.
5+
6+
Return the minimum possible diameter of the resulting tree.
7+
8+
The diameter of a tree is the length of the longest path between any two nodes in the tree.
9+
'''
10+
11+
class Solution:
12+
def minimumDiameterAfterMerge(self, edges1: List[List[int]], edges2: List[List[int]]) -> int:
13+
n = len(edges1)+1
14+
m = len(edges2)+1
15+
16+
17+
adj1 = self.buildAdjList(n,edges1)
18+
adj2 = self.buildAdjList(m,edges2)
19+
20+
d1 = self.find_diameter(n,adj1)
21+
d2 = self.find_diameter(m,adj2)
22+
comb = ceil(d1/2) + ceil(d2/2)+1
23+
return max(comb, d1,d2)
24+
25+
def buildAdjList(self,n,e):
26+
27+
graph = defaultdict(list)
28+
for a,b in e:
29+
graph[a].append(b)
30+
graph[b].append(a)
31+
return graph
32+
33+
34+
def find_diameter(self,n,adj):
35+
farthest_node,_ = self.find_farthest_node(n,adj,0)
36+
_,diameter = self.find_farthest_node(n,adj,farthest_node)
37+
return diameter
38+
39+
def find_farthest_node(self,n,adj,source_node):
40+
q = deque([source_node])
41+
visited = [False]*n
42+
visited[source_node] = True
43+
maxd = 0
44+
farthest_node =source_node
45+
while q:
46+
for _ in range(len(q)):
47+
cur = q.popleft()
48+
farthest_node = cur
49+
for n in adj[cur]:
50+
if not visited[n]:
51+
visited[n]=True
52+
q.append(n)
53+
if q:
54+
maxd+=1
55+
return farthest_node,maxd

0 commit comments

Comments
 (0)