java: add «3203. Find Minimum Diameter After Merging Two Trees»

URL:	https://leetcode.com/problems/find-minimum-diameter-after-merging-two-trees/
This commit is contained in:
Matej Focko 2024-12-24 23:29:10 +01:00
parent 1888a23f4e
commit b78dbab383
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,65 @@
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
class Solution {
private List<List<Integer>> makeGraph(int[][] edges) {
var n = edges.length + 1;
var g = new ArrayList<List<Integer>>();
for (int i = 0; i < n; ++i) {
g.add(new ArrayList<>());
}
for (var edge : edges) {
g.get(edge[0]).add(edge[1]);
g.get(edge[1]).add(edge[0]);
}
return g;
}
private int getDiameter(int[][] edges) {
var n = edges.length + 1;
var g = makeGraph(edges);
var deg = new int[n];
var q = new ArrayDeque<Integer>();
for (int i = 0; i < n; ++i) {
deg[i] = g.get(i).size();
if (deg[i] == 1) {
q.offer(i);
}
}
int levelsRemoved = 0;
int remaining = n;
while (remaining > 2) {
var size = q.size();
remaining -= size;
++levelsRemoved;
for (int i = 0; i < size; ++i) {
var u = q.poll();
for (var v : g.get(u)) {
--deg[v];
if (deg[v] == 1) {
q.offer(v);
}
}
}
}
return 2 * levelsRemoved + ((remaining == 2) ? 1 : 0);
}
public int minimumDiameterAfterMerge(int[][] edges1, int[][] edges2) {
var d1 = getDiameter(edges1);
var d2 = getDiameter(edges2);
var combined = (d1 / 2 + d1 % 2) + (d2 / 2 + d2 % 2) + 1;
return Math.max(combined, Math.max(d1, d2));
}
}