Bread first search | Brute force
Code\njava []\n\nclass Solution {\n    public int[] maxTargetNodes(int[][] edges1, int[][] edges2, int k) {\n        int n = edges1.length + 1;\n        int m =
# Code\n```java []\n\nclass Solution {\n    public int[] maxTargetNodes(int[][] edges1, int[][] edges2, int k) {\n        int n = edges1.length + 1;\n        int m = edges2.length + 1;\n\n        List<List<Integer>> tree1 = new ArrayList<>();\n        List<List<Integer>> tree2 = new ArrayList<>();\n\n        for (int i = 0; i < n; i++) tree1.add(new ArrayList<>());\n        for (int i = 0; i < m; i++) tree2.add(new ArrayList<>());\n\n        for (int[] edge : edges1) {\n            tree1.get(edge[0]).add(edge[1]);\n            tree1.get(edge[1]).add(edge[0]);\n        }\n\n\n        for (int[] edge : edges2) {\n            tree2.get(edge[0]).add(edge[1]);\n            tree2.get(edge[1]).add(edge[0]);\n        }\n\n        int f2 = 0;\n        for (int i = 0; i < m; i++) {\n            f2 = Math.max(f2, bfs(tree2, k - 1, i));\n        }\n\n        int[] answer = new int[n];\n        for (int i = 0; i < n; i++) {\n            answer[i] = f2 + bfs(tree1, k, i);\n        }\n\n        return answer;\n    }\n\n    public int bfs(List<List<Integer>> graph, int k, int src) {\n        Queue<Integer> q = new LinkedList<>();\n        boolean[] visited = new boolean[graph.size()];\n        q.add(src);\n        visited[src] = true;\n        int cnt = 0;\n\n        while (k >= 0) {\n            int sz = q.size();\n            cnt += sz;\n\n            for (int i = 0; i < sz; i++) {\n                int curr = q.poll();\n                for (int neighbor : graph.get(curr)) {\n                    if (!visited[neighbor]) {\n                        q.add(neighbor);\n                        visited[neighbor] = true;\n                    }\n                }\n            }\n            k--;\n        }\n\n        return cnt;\n    }\n}\n\n```
['Tree', 'Breadth-First Search', 'Queue', 'Java']