Maximum Target Nodes in Two Trees with BFS and Precomputation.
IntuitionApproachComplexity

Time complexity:
O(n^2 + m^2).


Space complexity:
O(n + m).

Code
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
<!-- Describe your approach to solving the problem. -->

# Complexity
- Time complexity:
O(n^2 + m^2).

- Space complexity:
O(n + m).

# Code
```cpp []
class Solution {
public:
    vector<int> maxTargetNodes(vector<vector<int>>& edges1,
                               vector<vector<int>>& edges2, int k) {

        int n = edges1.size() + 1, m = edges2.size() + 1;

        vector<int> ans(n, 0);

        vector<vector<int>> adj1(n), adj2(m);

        for (auto it : edges1) {
            int u = it[0];
            int v = it[1];
            adj1[u].push_back(v);
            adj1[v].push_back(u);
        }

        for (auto it : edges2) {
            int u = it[0];
            int v = it[1];
            adj2[u].push_back(v);
            adj2[v].push_back(u);
        }

        vector<int> V1 = precomputeValues(n, k, adj1);
        vector<int> V2 = precomputeValues(m, k - 1, adj2);

        int mV2 = *max_element(V2.begin(),V2.end());
        for (int i = 0; i < n; i++) {
            ans[i] = V1[i] + mV2;
        }
        return ans;
    }

    vector<int> precomputeValues(int n, int k, vector<vector<int>>& adj) {
        vector<int> value(n);
        for (int i = 0; i < n; i++) {
            vector<int> vis(n);
            value[i] += bfs(i, k, vis, adj);
        }
        return value;
    }

    int bfs(int node, int k, vector<int>& vis, vector<vector<int>>& adj) {
        if (k < 0)
            return 0;
        queue<pair<int, int>> q;
        int cnt = 0;
        //{lvl,node}
        q.push({0, node});
        vis[node] = 1;
        while (!q.empty()) {
            auto it = q.front();
            q.pop();
            int lvl = it.first;
            int cnode = it.second;
            if (lvl > k)
                continue;
            cnt++;
            for (auto it : adj[cnode]) {
                if (!vis[it]) {
                    q.push({lvl + 1, it});
                    vis[it] = 1;
                }
            }
        }
        return cnt;
    }
};
```
['C++']