Find Minimum Diameter After Merging Two Trees

Try to solve the Find Minimum Diameter After Merging Two Trees problem.

Statement

You are given two undirected trees: one with nn nodes labeled from 00 to n1n - 1, and another with mm nodes labeled from 00 to m1m - 1. Their structures are defined by two 2D2D integer arrays—edges1 of length n1n - 1 for the first tree, and edges2 of length m1m - 1 for the second. Each element edges1[i] = [aᵢ, bᵢ] represents an edge between nodes aaᵢ and bbᵢ in the first tree, and similarly, edges2[i] = [uᵢ, vᵢ] represents an edge in the second tree.

Your task is to connect any node from the first tree to any node from the second tree using a single edge. Return the smallest possible diameter of the resulting combined tree.

Note: The diameter of a tree is the length of the longest path between any two nodes in it.

Constraints:

  • 1<=n,m<=1051 <= n, m <= 10^5

  • edges1.length ==n1== n - 1

  • edges2.length ==m1== m - 1

  • edges1[i].length ==== edges2[i].length ==2== 2

  • edges1[i] = [ai, bi]

  • 0<=ai,bi<n0 <= a_i, b_i < n

  • edges2[i] = [ui, vi]

  • 0<=ui,vi<m0 <= u_i, v_i < m

  • The  edges1 and edges2 always represent valid trees.

Examples

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.