Solution: Find Minimum Diameter After Merging Two Trees
Let’s solve the Find Minimum Diameter After Merging Two Trees problem using the Tree Breadth-First Search pattern.
We'll cover the following
Statement
You are given two undirected trees: one with edges1
of length edges2
of length edges1[i] = [aᵢ, bᵢ]
represents an edge between nodes edges2[i] = [uᵢ, vᵢ]
represents an edge in the second tree.
Your task is to connect any node from the first tree to any one 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:
edges1.length
edges2.length
edges1[i].length
edges2[i].length
edges1[i] = [a
i
, b
i
]
edges2[i] = [u
i
, v
i
]
The input is generated such that
edges1
andedges2
represent valid trees.
Solution
To solve this problem, we use the tree breadth-first search (BFS) pattern. The intuition behind this pattern lies in the fact that breadth-first search naturally discovers the shortest paths level by level, making it ideal for finding the farthest nodes in a tree. We can accurately and efficiently find a tree’s diameter by doing two passes of breadth-first search.
Here’s how two passes of breadth-first search work:
Farthest node from any node: If we start at an arbitrary node and perform a breadth-first search in any tree, we will eventually reach the farthest node from the start. Let’s call this node
. Second farthest node: From node
, perform another breadth-first search. The farthest node found in this second breadth-first search will be the other end of the diameter. The distance between these two nodes is the diameter of the tree.
Once we know the diameters of both trees individually, we don’t need to test every node pairing. Instead, we can rely on a mathematical insight.
The worst-case diameter when connecting two trees is bounded by
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.