Problem Statement
There exist two undirected trees with n
and m
nodes, with distinct labels in ranges [0, n - 1]
and [0, 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 are also given an integer k
.
Node u
is target to node v
if the number of edges on the path from u
to v
is less than or equal to k
. Note that a node is always target to itself.
Return an array of n
integers answer
, where answer[i]
is the maximum possible number of nodes target to node i
of the first tree if you have to connect one node from the first tree to another node in the second tree.
Note that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.
LeetCode
Constraints
2 <= n, m <= 1000
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.
0 <= k <= 1000
Examples
Example 1:

Input: edges1 = [
[0,1],
[0,2],
[2,3],
[2,4]
],
edges2 = [
[0,1],
[0,2],
[0,3],
[2,7],
[1,4],
[4,5],
[4,6]
],
k = 2
Output: [9,7,9,8,8]
Explanation:
For i = 0, connect node 0 from the first tree to node 0 from the second tree.
For i = 1, connect node 1 from the first tree to node 0 from the second tree.
For i = 2, connect node 2 from the first tree to node 4 from the second tree.
For i = 3, connect node 3 from the first tree to node 4 from the second tree.
For i = 4, connect node 4 from the first tree to node 4 from the second tree.
Example 2:

Input: edges1 = [
[0,1],
[0,2],
[0,3],
[0,4]
],
edges2 = [
[0,1],
[1,2],
[2,3]
],
k = 1
Output: [6,3,3,3,3]
Explanation:
For every i, connect node i of the first tree with any node of the second tree.
Different Approaches
1️⃣ DFS
Code:
class Solution {
public:
// Helper DFS function to count number of nodes reachable from 'node' within distance 'k'
int dfs(vector<vector<int>>& tree, vector<int>& visited, int node, int k) {
if (k < 0) return 0;
int count = 1; // Count self
for (int neighbor : tree[node]) {
if (!visited[neighbor]) {
visited[neighbor] = 1;
count += dfs(tree, visited, neighbor, k - 1); // Recurse with reduced distance
visited[neighbor] = 0; // Backtrack
}
}
return count;
}
vector<int> maxTargetNodes(vector<vector<int>>& edges1, vector<vector<int>>& edges2, int k) {
int n = 0, m = 0;
// Step 1: Determine the number of nodes in each tree
for (auto& edge : edges1)
n = max(n, max(edge[0], edge[1]));
for (auto& edge : edges2)
m = max(m, max(edge[0], edge[1]));
n++; m++; // Convert max index to count
// Step 2: Build adjacency list for both trees
vector<vector<int>> tree1(n), tree2(m);
for (auto& edge : edges1) {
tree1[edge[0]].push_back(edge[1]);
tree1[edge[1]].push_back(edge[0]);
}
for (auto& edge : edges2) {
tree2[edge[0]].push_back(edge[1]);
tree2[edge[1]].push_back(edge[0]);
}
// Step 3: For each node in tree1, count how many nodes are within distance k
vector<int> result(n, 0); // Final result for each node in tree1
vector<int> visitedTree1(n, 0); // Visited array for tree1
for (int node = 0; node < n; node++) {
visitedTree1[node] = 1; // Mark node as visited
result[node] = dfs(tree1, visitedTree1, node, k); // Run DFS from this node
visitedTree1[node] = 0; // Unmark for next iteration
}
// Step 4: In tree2, compute the maximum number of nodes reachable from any node within (k - 1) distance
int maxReachableInTree2 = 0;
vector<int> visitedTree2(m, 0);
for (int node = 0; node < m; node++) {
visitedTree2[node] = 1;
maxReachableInTree2 = max(maxReachableInTree2, dfs(tree2, visitedTree2, node, k - 1));
visitedTree2[node] = 0;
}
// Step 5: Add max reachable nodes in tree2 to each node's answer in tree1
for (int i = 0; i < n; i++) {
result[i] += maxReachableInTree2;
}
return result;
}
};
Complexity Analysis:
Let:
n
= number of nodes in tree1
m
= number of nodes in tree2
k
= maximum allowed path length
- Time Complexity:
- DFS from each node in tree1:
O(n * n)
worst-case (for dense trees), but limited byk
- Practically:
O(n * B ^ k)
, whereB
is branching factor
- Practically:
- DFS from each node in tree2:
O(m * B^k)
- Final Time:
O(n * B^k + m * B^k)
-> efficient whenk
is small(k ≤ 10)
- DFS from each node in tree1:
- Space Complexity:
- Graphs:
O(n + m)
- Visited arrays:
O(n + m)
- Call stack:
O(k)
per DFS
- Graphs:
2️⃣ BFS
Code:
class Solution {
public:
// BFS to count how many nodes are reachable from `start` within `maxDepth`
int bfs(vector<vector<int>>& tree, int start, int maxDepth) {
int n = tree.size();
vector<bool> visited(n, false);
queue<pair<int, int>> q;
visited[start] = true;
q.push({start, 0});
int count = 0;
while (!q.empty()) {
auto [node, depth] = q.front();
q.pop();
if (depth > maxDepth) continue;
count++;
for (int neighbor : tree[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push({neighbor, depth + 1});
}
}
}
return count;
}
vector<int> maxTargetNodes(vector<vector<int>>& edges1, vector<vector<int>>& edges2, int k) {
int n = 0, m = 0;
for (auto& edge : edges1)
n = max(n, max(edge[0], edge[1]));
for (auto& edge : edges2)
m = max(m, max(edge[0], edge[1]));
n++; m++;
// Build adjacency lists
vector<vector<int>> tree1(n), tree2(m);
for (auto& edge : edges1) {
tree1[edge[0]].push_back(edge[1]);
tree1[edge[1]].push_back(edge[0]);
}
for (auto& edge : edges2) {
tree2[edge[0]].push_back(edge[1]);
tree2[edge[1]].push_back(edge[0]);
}
vector<int> result(n);
// Step 1: For each node in Tree 1, compute reachable nodes using BFS with depth k
for (int i = 0; i < n; ++i) {
result[i] = bfs(tree1, i, k);
}
// Step 2: In Tree 2, compute max reachable nodes from any node using BFS with depth (k-1)
int maxTree2Reach = 0;
for (int j = 0; j < m; ++j) {
maxTree2Reach = max(maxTree2Reach, bfs(tree2, j, k - 1));
}
// Step 3: Add Tree2 max reach to all Tree1 answers
for (int i = 0; i < n; ++i) {
result[i] += maxTree2Reach;
}
return result;
}
};
Complexity Analysis:
Let:
n
= nodes in tree1,
m
= nodes in tree2,
k
= max distance
- Time Complexity:
- For each node in tree1:
O(n * n)
in worst-case (dense tree, k = n) - For each node in tree2:
O(m * m)
- Total:
O(n^2 + m^2)
- For each node in tree1:
- Space Complexity:
O(n + m)
- For adjacency lists and visited arrays