Skip to content

3203. Find Minimum Diameter After Merging Two Trees

Description

There exist two undirected trees with n and m nodes, numbered from 0 to n - 1 and from 0 to m - 1, respectively. You are given two 2D integer arrays edges1 and edges2 of lengths n - 1 and m - 1, respectively, where edges1[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the first tree and edges2[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the second tree.

You must connect one node from the first tree with another node from the second tree with an edge.

Return the minimum possible diameter of the resulting tree.

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

 

Example 1:

Input: edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]

Output: 3

Explanation:

We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.

Example 2:

Input: edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]

Output: 5

Explanation:

We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.

 

Constraints:

  • 1 <= n, m <= 105
  • edges1.length == n - 1
  • edges2.length == m - 1
  • edges1[i].length == edges2[i].length == 2
  • edges1[i] = [ai, bi]
  • 0 <= ai, bi < n
  • edges2[i] = [ui, vi]
  • 0 <= ui, vi < m
  • The input is generated such that edges1 and edges2 represent valid trees.

 

Solutions

Solution: Depth-First Search

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

 

JavaScript

js
/**
 * @param {number[][]} edges1
 * @param {number[][]} edges2
 * @return {number}
 */
const minimumDiameterAfterMerge = function (edges1, edges2) {
  const getDiameter = edges => {
    const n = edges.length + 1;
    const graph = Array.from({ length: n }, () => []);

    for (const [a, b] of edges) {
      graph[a].push(b);
      graph[b].push(a);
    }
    let maxDiameter = 0;
    let edgeNode = 0;

    const dfsTree = (node, prev, diameter) => {
      if (maxDiameter < diameter) {
        maxDiameter = diameter;
        edgeNode = node;
      }

      for (const nextNode of graph[node]) {
        if (nextNode === prev) continue;

        dfsTree(nextNode, node, diameter + 1);
      }
    };

    dfsTree(0, -1, 0);
    dfsTree(edgeNode, -1, 0);

    return maxDiameter;
  };

  const diameter1 = getDiameter(edges1);
  const diameter2 = getDiameter(edges2);
  const mergedDiameter = Math.ceil(diameter1 / 2) + Math.ceil(diameter2 / 2) + 1;

  return Math.max(diameter1, diameter2, mergedDiameter);
};

Released under the MIT license