Java - BFS
\n\n# Code\njava []\nclass Solution {\n    public int[] maxTargetNodes(int[][] edges1, int[][] edges2, int k) {\n        Map<Integer, List<Integer>> graph1 = bu
\n\n# Code\n```java []\nclass Solution {\n    public int[] maxTargetNodes(int[][] edges1, int[][] edges2, int k) {\n        Map<Integer, List<Integer>> graph1 = buildGraph(edges1);\n        int n = edges1.length + 1;\n        int[] cnt1 = new int[n];\n        for (int from = 0; from < n; from++) {\n            cnt1[from] = getNodesWithinK(graph1, from, k);\n        }\n\n        Map<Integer, List<Integer>> graph2 = buildGraph(edges2);\n        int m = edges2.length + 1;\n        int[] cnt2 = new int[m];\n        int max = -1;\n        for (int from = 0; from < m; from++) {\n            cnt2[from] = getNodesWithinK(graph2, from, k-1);\n            max = Math.max(max, cnt2[from]);\n        };\n\n        // System.out.println("cnt1: " + Arrays.toString(cnt1));\n        // System.out.println("cnt2: " + Arrays.toString(cnt2));\n\n        int[] res = new int[n];\n        for (int i = 0; i < n; i++) {\n            res[i] = cnt1[i] + max;\n        }\n        return res;\n    }\n\n    int getNodesWithinK (Map<Integer, List<Integer>> graph, int from, int k) {\n        Queue<int[]> queue = new LinkedList<>();\n        queue.offer(new int[]{from, -1});\n\n        int cnt = 0;\n        int layer = 0;\n        while (!queue.isEmpty() && layer <= k) {\n            int size = queue.size();\n            for (int i = 0; i < size; i++) {\n                int[] arr = queue.poll();\n                int curr = arr[0], parent = arr[1];\n                for (int next : graph.get(curr)) {\n                    if (next == parent) continue;\n                    queue.offer(new int[]{next, curr});\n                }\n                cnt++;\n            }\n            layer++;\n        }\n        return cnt;\n    }\n\n    Map<Integer, List<Integer>> buildGraph(int[][] edges) {\n        int n = edges.length + 1;\n        Map<Integer, List<Integer>> graph = new HashMap<>();\n\n        for (int[] edge : edges) {\n            int a = edge[0], b = edge[1];\n            graph.computeIfAbsent(a, k -> new ArrayList<>()).add(b);\n            graph.computeIfAbsent(b, k -> new ArrayList<>()).add(a);\n        }\n\n        return graph;\n    }  \n}\n```
['Java']