Find Minimum Diameter After Merging Two Trees

Connect two trees with one edge minimizing the resulting tree's diameter.

Hard
Time O(n + m) Space O(n + m)
LeetCode
6 min read
tree bfs graph

Problem#

You are given two trees with edge lists edges1 and edges2. You must add exactly one edge between any node of tree 1 and any node of tree 2, forming a single tree. Return the minimum possible diameter of the merged tree.

Examples#

  • edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]3.
  • Two paths of length 4 each → connect midpoints, merged diameter = max(d1, d2, ceil(d1/2)+ceil(d2/2)+1).

Constraints#

  • 1 <= n, m <= 10^5. Each input is a valid tree.

Hints#

Hint 1
Connecting two trees optimally means joining their centroid-like middles.
Hint 2
Best new diameter = max(d1, d2, ceil(d1/2) + ceil(d2/2) + 1).

Approach#

Compute each tree’s diameter d1, d2 independently via two BFS sweeps (farthest-from-any, then farthest-from-that). The merged diameter is max(d1, d2, ceil(d1/2) + ceil(d2/2) + 1) — connecting the trees at their radii midpoints.

Solution#

Find Minimum Diameter After Merging Two Trees
class Solution {
public:
int minimumDiameterAfterMerge(vector<vector<int>>& edges1, vector<vector<int>>& edges2) {
int d1 = treeDiameter(edges1);
int d2 = treeDiameter(edges2);
int combined = (d1 + 1) / 2 + (d2 + 1) / 2 + 1;
return max({d1, d2, combined});
}
private:
int treeDiameter(vector<vector<int>>& edges) {
int n = edges.size() + 1;
if (n == 1) return 0;
vector<vector<int>> g(n);
for (auto& e : edges) { g[e[0]].push_back(e[1]); g[e[1]].push_back(e[0]); }
auto bfsFarthest = [&](int src) -> pair<int,int> {
vector<int> dist(n, -1);
queue<int> q;
q.push(src); dist[src] = 0;
int far = src;
while (!q.empty()) {
int u = q.front(); q.pop();
if (dist[u] > dist[far]) far = u;
for (int v : g[u]) if (dist[v] == -1) {
dist[v] = dist[u] + 1;
q.push(v);
}
}
return {far, dist[far]};
};
auto [a, _] = bfsFarthest(0);
auto [b, d] = bfsFarthest(a);
return d;
}
};

Editorial#

Diameter of a tree is found by the two-BFS trick: any farthest node from an arbitrary start is one endpoint; the farthest from that endpoint is the other. To merge: the best joining edge lands at radii (ceil(d/2)) of each tree so that the new tree’s longest path through the bridge is balanced — that’s why the third term uses ceiling halves plus one for the new edge.

Complexity#

  • Time: O(n + m).
  • Space: O(n + m).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.