1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| class Solution { int n; List<Integer>[] g; int[] ans, size;
public int[] sumOfDistancesInTree(int n, int[][] edges) { this.n = n; g = new ArrayList[n]; Arrays.setAll(g, e -> new ArrayList<>()); for (int[] edge : edges) { int x = edge[0], y = edge[1]; g[x].add(y); g[y].add(x); } ans = new int[n]; size = new int[n]; dfs(0, -1, 0); reroot(0, -1); return ans; }
private void dfs(int x, int pa, int depth) { ans[0] += depth; size[x] = 1; for (int y : g[x]) { if (y != pa) { dfs(y, x, depth + 1); size[x] += size[y]; } } }
private void reroot(int x, int pa) { for (int y : g[x]) { if (y != pa) { ans[y] = ans[x] + n - 2 * size[y]; reroot(y, x); } } } }
|