Skip to content

Create 3203. Find Minimum Diameter After Merging Two Trees #670

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions 3203. Find Minimum Diameter After Merging Two Trees
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class Solution {
public:
void dfs(int node, int par, int dis, int &maxi, vector<vector<int>>&adj, int &far){
if(dis>maxi){
maxi = dis;
far = node;
}
for(auto it:adj[node]){
if(it!=par){
dfs(it, node, dis+1, maxi, adj, far);
}
}
}

int minimumDiameterAfterMerge(vector<vector<int>>& edges1, vector<vector<int>>& edges2) {
int n = edges1.size()+1;
int m = edges2.size()+1;
vector<vector<int>>adj1(n);
vector<vector<int>>adj2(m);
for(auto it: edges1){
adj1[it[0]].push_back(it[1]);
adj1[it[1]].push_back(it[0]);
}

int maxi1 = 0;
int far = 0;
dfs(0, -1, 0, maxi1, adj1, far);

maxi1 = 0;
int far1 = 0;
dfs(far, -1, 0, maxi1, adj1, far1);

for(auto it: edges2){
adj2[it[0]].push_back(it[1]);
adj2[it[1]].push_back(it[0]);
}

int maxi2 = 0;
far = 0;
dfs(0, -1, 0, maxi2, adj2, far);

maxi2 = 0;
int far2 = 0;
dfs(far, -1, 0, maxi2, adj2, far2);

int tmp1 = (maxi1+1)/2;
int tmp2 = (maxi2+1)/2;
int mrg = tmp1+tmp2+1;
return max(maxi1, max(mrg, maxi2));
}
};
Loading