Find Minimum Diameter After Merging Two Trees - Problem
Imagine you have two separate trees - like two different family trees or organizational charts - and you need to connect them with a single bridge to create one unified tree structure.
Given two undirected trees with n and m nodes respectively:
- Tree 1: nodes numbered 0 to n-1, connected by edges in
edges1 - Tree 2: nodes numbered 0 to m-1, connected by edges in
edges2
You must connect exactly one node from tree 1 to one node from tree 2 with a new edge. Your goal is to minimize the diameter of the resulting merged tree.
The diameter is the length of the longest path between any two nodes in the tree - think of it as the "worst-case distance" you'd have to travel to get from one end of the tree to the other.
Return: The minimum possible diameter after optimally connecting the two trees.
Input & Output
example_1.py β Basic Case
$
Input:
edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]
βΊ
Output:
3
π‘ Note:
Tree1 has diameter 2 (from node 1 to 3 via 0). Tree2 has diameter 1. Optimal connection gives diameter max(2, 1, ceil(2/2) + ceil(1/2) + 1) = max(2, 1, 3) = 3.
example_2.py β Equal Trees
$
Input:
edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[3,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[3,7]]
βΊ
Output:
5
π‘ Note:
Both trees have the same structure with diameter 4. The optimal diameter is max(4, 4, ceil(4/2) + ceil(4/2) + 1) = max(4, 4, 5) = 5.
example_3.py β Single Nodes
$
Input:
edges1 = [], edges2 = []
βΊ
Output:
1
π‘ Note:
Both trees have single nodes (diameter 0). After connecting them: max(0, 0, ceil(0/2) + ceil(0/2) + 1) = max(0, 0, 1) = 1.
Constraints
- 1 β€ n, m β€ 105
- edges1.length == n - 1
- edges2.length == m - 1
- edges1[i].length == edges2[i].length == 2
- 0 β€ ai, bi < n
- 0 β€ ui, vi < m
- Both input graphs are trees (connected and acyclic)
Visualization
Tap to expand
Understanding the Visualization
1
Measure Each Island
Find the diameter (longest road) in each island's road network
2
Locate Centers
Identify the central locations that minimize travel distances
3
Three Journey Types
Consider journeys within island1, within island2, or across the bridge
4
Bridge Journey Length
Cross-bridge journey = radius1 + bridge(1) + radius2
5
Choose Worst Case
The longest of these three journey types is your answer
Key Takeaway
π― Key Insight: The optimal diameter is determined by the worst-case journey among three types: staying within each original tree, or crossing the bridge. Connecting the centers of both trees minimizes the cross-bridge journey length.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code