Skip to content

Instantly share code, notes, and snippets.

@maximpn
Created September 20, 2021 22:07
Show Gist options
  • Save maximpn/89c62fa7a40e80c721364df2db3747a8 to your computer and use it in GitHub Desktop.
Save maximpn/89c62fa7a40e80c721364df2db3747a8 to your computer and use it in GitHub Desktop.
class Solution {
int[] ans, count;
List<Set<Integer>> graph;
int N;
public int[] sumOfDistancesInTree(int N, int[][] edges) {
this.N = N;
graph = new ArrayList<Set<Integer>>();
ans = new int[N];
count = new int[N];
Arrays.fill(count, 1);
for (int i = 0; i < N; ++i)
graph.add(new HashSet<Integer>());
for (int[] edge: edges) {
graph.get(Math.min(edge[0], edge[1])).add(Math.max(edge[0], edge[1]));
}
dfs(0, -1);
dfs2(0, -1);
return ans;
}
public void dfs(int node, int parent) {
for (int child: graph.get(node)) {
dfs(child, node);
count[node] += count[child];
ans[node] += ans[child] + count[child];
}
}
public void dfs2(int node, int parent) {
for (int child: graph.get(node)) {
ans[child] = ans[node] - count[child] + N - count[child];
dfs2(child, node);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment