#3372
Maximize the Number of Target Nodes After Connecting Trees I
MediumTreeDepth-First SearchBreadth-First SearchTree TraversalGraph Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(n + m) |
💡
Intuition
Time O(n + m)Space O(n + m)
Use BFS/DFS to precompute reachable nodes for both trees. For each node in the first tree, combine its reachable nodes with those from the second tree to maximize targets.
⚙️
Algorithm
3 steps- 1Step 1: Perform BFS/DFS on the first tree to find reachable nodes within distance k.
- 2Step 2: Perform BFS/DFS on the second tree to find reachable nodes within distance k-1.
- 3Step 3: For each node in the first tree, sum the counts of reachable nodes from both trees.
solution.py3 lines
1def maxTargetNodes(edges1, edges2, k):
2 # BFS/DFS implementation
3 return resultℹ
Complexity note: Each tree is traversed once, leading to linear complexity relative to their sizes.
- 1Precomputation of reachable nodes is crucial.
- 2Distance constraints can be managed with BFS/DFS.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.