> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Find Minimum Diameter After Merging Two Trees

> Tested Python solution for LeetCode 3203 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 3203, [Hard](/catalog/hard). Topics: [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Graph Theory](/catalog/topics/graph-theory). [View on LeetCode](https://leetcode.com/problems/find-minimum-diameter-after-merging-two-trees/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 3203   # by problem number
lcpy gen -s find_minimum_diameter_after_merging_two_trees   # by problem name
```

## Problem

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.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2024/04/22/example11-transformed.png)

```
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](https://assets.leetcode.com/uploads/2024/04/22/example211.png)

```
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 <= 10^5`
* `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.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_minimum_diameter_after_merging_two_trees/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_minimum_diameter_after_merging_two_trees/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque


class Solution:
    # Time: O(n + m)
    # Space: O(n + m)
    def minimum_diameter_after_merge(self, edges1: list[list[int]], edges2: list[list[int]]) -> int:
        d1 = self._diameter(len(edges1) + 1, edges1)
        d2 = self._diameter(len(edges2) + 1, edges2)
        return max(d1, d2, (d1 + 1) // 2 + (d2 + 1) // 2 + 1)

    def _diameter(self, n: int, edges: list[list[int]]) -> int:
        adj: list[list[int]] = [[] for _ in range(n)]
        for a, b in edges:
            adj[a].append(b)
            adj[b].append(a)

        def farthest(src: int) -> tuple[int, int]:
            dist = [-1] * n
            dist[src] = 0
            queue = deque([src])
            last = src
            while queue:
                node = queue.popleft()
                last = node
                for nxt in adj[node]:
                    if dist[nxt] == -1:
                        dist[nxt] = dist[node] + 1
                        queue.append(nxt)
            return last, dist[last]

        endpoint, _ = farthest(0)
        _, diameter = farthest(endpoint)
        return diameter
```

## Complexity

| Time | Space |
| - | - |
| O(n + m) | O(n + m) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.