Python3 Double DFS O(km+kn) (Beats 99.3%)
\nclass Solution:\n    def maxTargetNodes(self, edges1: List[List[int]], edges2: List[List[int]], k: int) -> List[int]:\n        if k == 0:\n            return 
```\nclass Solution:\n    def maxTargetNodes(self, edges1: List[List[int]], edges2: List[List[int]], k: int) -> List[int]:\n        if k == 0:\n            return [1] * (len(edges1)+1)\n        \n        def wrapper(edges, k):\n            n = len(edges) + 1\n            g = [[] for _ in range(n)]\n            \n            for u, v in edges:\n                g[u].append(v)\n                g[v].append(u)\n                \n            cnt = [[0]*(k+1) for _ in range(n)] # cnt[i][j] is number of nodes has distance j to node i\n        \n            def dfs1(to, fa):\n                nonlocal cnt\n                cnt[to][0] += 1\n                for nei in g[to]:\n                    if nei == fa:\n                        continue\n                    dfs1(nei, to)\n                    for d in range(1, k+1):\n                        cnt[to][d] += cnt[nei][d-1]\n                return\n            \n            dfs1(0, -1)\n        \n            # propagate\n            def dfs2(to, fa):\n                nonlocal cnt\n                for nei in g[to]:\n                    if nei == fa:\n                        continue\n                    for d in range(k, 0, -1):\n                        if d == 1:\n                            cnt[nei][d] += cnt[to][d-1]\n                        else:\n                            cnt[nei][d] += cnt[to][d-1] - cnt[nei][d-2]\n                    dfs2(nei, to)\n            \n            dfs2(0, -1)\n            return cnt\n            \n        cnt1 = wrapper(edges1, k)\n        cnt2 = wrapper(edges2, k-1)\n        tree2_max = max(sum(l) for l in cnt2)\n        return [sum(l) + tree2_max for l in cnt1]\n        \n        \n\n```
['Depth-First Search', 'Python3']