Problem Description
Given two undirected trees (one with n nodes and the other with m nodes) represented by edge lists, you must connect one node from the first tree to one node from the second tree with an edge. The objective is to choose a connection that minimizes the diameter of the resulting tree. The diameter of a tree is defined as the length of the longest path between any two nodes in the tree.
Key Insights
- The diameter of a tree can be computed using two BFS/DFS traversals: one to find an endpoint and the second to compute the farthest distance from that endpoint.
- For any tree, the "radius" – the minimum possible maximum distance from a selected center node – is given by (diameter + 1) // 2.
- When merging the two trees by connecting one node from each, the longest path may come from:
- The diameter in the first tree.
- The diameter in the second tree.
- A combined path that goes from the farthest leaf in tree1 (from its center) to the farthest leaf in tree2 (from its center) plus the connecting edge.
- Therefore, the minimum possible diameter of the merged tree is: max(diameter1, diameter2, radius1 + radius2 + 1)
Space and Time Complexity
Time Complexity: O(n + m)
Space Complexity: O(n + m)
Solution
We first compute the diameter for each tree using two traversals (BFS or DFS). For each tree:
- Start from an arbitrary node to perform a BFS/DFS to determine the farthest node.
- From that farthest node, perform another BFS/DFS to find the farthest distance which will be the tree's diameter.
- Calculate the radius as (diameter + 1) // 2. After obtaining diameters (and thus radii) for both trees, the answer is given by the maximum among the two diameters and (radius1 + radius2 + 1), where the additional 1 accounts for the connecting edge between the two trees.