Java solution using bfs beats 100%
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n BFS to Count Nodes Wit
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n BFS to Count Nodes Within Distance\nUsing a helper function f, we:\n\nStart a BFS traversal from a given node i.\nCount all nodes within a distance k for Tree 1 and k-1 for Tree 2.\n Iterate and Compute Results\nFor each node in Tree 1:\nCompute the maximum number of nodes within k-1 distance in Tree 2 (by iterating over all nodes in Tree 2).\nAdd this value to the number of nodes within k distance in Tree 1.\nFinally, store the sum in the results array. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n     public int[] maxTargetNodes(int[][] edges1, int[][] edges2, int k) {\n        int[]ans=new int[edges1.length+1];\n        if(k==0) {\n            Arrays.fill(ans,1);\n            return ans;\n        }\n        List<List<Integer>> list1=createGraph(edges1);\n        List<List<Integer>> list2=createGraph(edges2);\n        int max=0;\n        for(int i=0;i<=edges2.length;i++) {\n            max=Math.max(max,f(i,list2,k-1));\n        }\n        for(int i=0;i<=edges1.length;i++) {\n            ans[i] = max + f(i,list1,k);\n        }\n        return ans;\n    }\n    private List<List<Integer>> createGraph(int[][]arr) {\n        int m =arr.length;\n        List<List<Integer>> graph=new ArrayList<>();\n        for(int i=0;i<=m;i++) graph.add(new ArrayList<>());\n        for(int[]i:arr) {\n            graph.get(i[0]).add(i[1]);\n            graph.get(i[1]).add(i[0]);\n        }\n        return graph;\n    }\n    private int f(int i,List<List<Integer>>graph,int k) {\n        Queue<int[]>q=new LinkedList<>();\n        q.add(new int[]{i,0});\n        boolean[]vis=new boolean[graph.size()];\n        vis[i]=true;\n        int cnt=0;\n        while(!q.isEmpty()) {\n            int[]curr=q.poll();\n            cnt++;\n            if(curr[1]==k) continue;\n            for(int j:graph.get(curr[0])) {\n                if(!vis[j]) {\n                    vis[j]=true;\n                    q.add(new int[]{j,curr[1]+1});\n                }\n            }\n        }\n        return cnt;\n    }\n}\n```
['Breadth-First Search', 'Java']