BFS solution - Python3
Intuition\nWe have to the target nodes at \'k\' distance which gives us the idea to use BFS.\n\n# Approach\nWe are asked to maximize the output in the quesion. 
# Intuition\nWe have to the target nodes at \'k\' distance which gives us the idea to use BFS.\n\n# Approach\nWe are asked to maximize the output in the quesion. If we see carefully, the only changing parameter in the output array is the node from tree1. Which means we can get the maximum degree of a node from tree2 connect that node to every node from tree1 to get the maximum output.\nNote - Since we are connecting a node from tree1 to tree2 the distance reduces to \'k-1\' for tree2.\nSo, we can get the node which has the maximum target nodes in tree2 at distance "K-1" and add this value to every node from tree1 in the resultant array.\n\n# Complexity\n- Time complexity:\nFor tree2 - O(M*(V2 + E2))\nFor tree1 - O(N*(V1 + E1))\nTotal = M^2 + N^2 (in the worst case if k is very high)\n\n(Please correct me if I am wrong!)\n\n- Space complexity:\nTotal = O(N + M) (using a hashmap to store trees)\n\n# Code\n```python3 []\nclass Solution:\n    def maxTargetNodes(self, edges1: List[List[int]], edges2: List[List[int]], k: int) -> List[int]:\n        tree2 = defaultdict(list)\n        for u,v in edges2:\n            tree2[u].append(v)\n            tree2[v].append(u)\n\n        # bfs to find the no of nodes at dist \'d\' from the curr node in tree\n        def bfs(node, d, tree):\n            q = deque([node])\n            visited = set()\n            res = 0\n            while q and d>=0: # every node is target to itself\n                res += len(q)\n                for _ in range(len(q)):\n                    curr = q.popleft()\n                    visited.add(curr)\n                    for ele in tree[curr]:\n                        if ele not in visited:\n                            q.append(ele)\n                d -= 1\n            return res\n\n        # getting the maximum degree from tree2 so that node from tree1 can connect and maximixe it\'s target nodes.\n        max_d2 = float(\'-inf\')\n        for node in tree2:\n            d2 = bfs(node, k-1, tree2)\n            max_d2 = max(max_d2, d2)\n        \n        tree1 = defaultdict(list)\n        for u,v in edges1:\n            tree1[u].append(v)\n            tree1[v].append(u)\n        \n        # getting the degree from tree1 first and then adding the max value we have from tree2 to maximize the overall output.\n        res = [0]*len(tree1)\n        for node in tree1:\n            d1 = bfs(node, k, tree1)\n            res[node] = (d1 + max_d2)\n        return res\n```
['Python3']