BFS, Dictionary
Complexity

Time complexity:O(nlogn)


Space complexity:O(n)

Code
# Complexity
- Time complexity:
O(nlogn)

- Space complexity:
O(n)

# Code
```python3 []
from collections import deque
from operator import itemgetter

class Solution:
    def maxTargetNodes(self, edges1: List[List[int]], edges2: List[List[int]], k: int) -> List[int]:

        # build an adjacency list
        def buildGraph(edges):

            graph = defaultdict(list)

            for u, v in edges:
                graph[u].append(v)
                graph[v].append(u)
            return graph

        def getReachCount(edges, reach):

            edges = buildGraph(edges)

            reachCount = {}

            for i in edges.keys():
                # BFS approach essentially
                q = deque()

                if reach < 1:
                    
                    reachCount[i] = 1 if reach >= 0 else 0
                    continue

                q.append((i, 0, None))
                count = 0

                while q:
                    node, dist, prev = q.popleft()
                    if dist + 1 > reach:
                        continue

                    for edge in edges[node]:

                        # so that we don't loop around
                        if edge == prev:
                            continue

                        q.append((edge, dist + 1, node))
                        count += 1
                
                # the +1 is to account for the 
                reachCount[i] = count + 1
            
            return reachCount

        rc1 = getReachCount(edges1, k)
        # distance = 1 to attach it to the other node, kence k-1
        rc2 = getReachCount(edges2, k-1)

        # get the best match
        max_reach2 = max(rc2.values())  

        # sorte based on the graph nodes as a dictionary
        # does not maintain order
        rc1 = sorted(rc1.items(), key=itemgetter(0))
        ans = [i[1] + max_reach2  for i in rc1]

        return ans

```
['Python3']