/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution { intN=510, M = 4 * N, idx = 0; int[] he = newint[N], e = newint[M], ne = newint[M]; boolean[] visited = newboolean[N];
privatevoidadd(int a, int b) { e[idx] = b; ne[idx] = he[a]; he[a] = idx++; }
public List<Integer> distanceK(TreeNode root, TreeNode target, int k) { Arrays.fill(he, -1); dfs(root); List<Integer> ans = newArrayList<>(); Deque<Integer> queue = newArrayDeque<>(); queue.offer(target.val); visited[target.val] = true; while (!queue.isEmpty() && k >= 0) { intsize= queue.size(); while (size-- > 0) { intcur= queue.poll(); if (k == 0) { ans.add(cur); continue; } for (inti= he[cur]; i != -1; i = ne[i]) { intj= e[i]; if (!visited[j]) { queue.offer(j); visited[j] = true; } } } --k; } return ans; }
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution { intN=510, M = 4 * N, idx = 0; int[] he = newint[N], e = newint[M], ne = newint[M]; boolean[] visited = newboolean[N]; List<Integer> ans;
privatevoidadd(int a, int b) { e[idx] = b; ne[idx] = he[a]; he[a] = idx++; }
public List<Integer> distanceK(TreeNode root, TreeNode target, int k) { ans = newArrayList<>(); Arrays.fill(he, -1); dfs(root); visited[target.val] = true; find(target.val, k, 0); return ans; }
privatevoidfind(int node, int k, int cur) { if (cur == k) { ans.add(node); return; } for (inti= he[node]; i != -1; i = ne[i]) { intj= e[i]; if (!visited[j]) { visited[j] = true; find(j, k, cur + 1); } } }
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution { Map<Integer, List<Integer>> adj = newHashMap<>(); boolean[] visited = newboolean[510]; List<Integer> ans = newArrayList<>();
privatevoidadd(int a, int b) { adj.computeIfAbsent(a, key -> newArrayList<>()).add(b); }
public List<Integer> distanceK(TreeNode root, TreeNode target, int k) { dfs(root); visited[target.val] = true; find(target.val, k, 0); return ans; }
privatevoidfind(int node, int k, int cur) { if (cur == k) { ans.add(node); return; } List<Integer> list = adj.get(node); if (list == null) return; for (Integer i : list) { if (!visited[i]) { visited[i] = true; find(i, k, cur + 1); } } }