1
var sumOfDistancesInTree = function (n, edges) {3
for (let [start, end] of edges) {4
if (!graph[start]) graph[start] = [];5
if (!graph[end]) graph[end] = [];6
graph[start].push(end);7
graph[end].push(start);10
let visited = new Set(),13
// Find the sum distance from node O to all other nodes and the total children of each node14
function dfs(node, sum = 0) {16
distanceFromZero += sum;17
if (!graph[node]) return;19
for (let nextNode of graph[node]) {20
if (visited.has(nextNode)) continue;21
child += dfs(nextNode, sum + 1);23
totalChildren[node] = child;28
let dp = [distanceFromZero];30
function findDistance(node) {32
if (!graph[node]) return;33
for (let nextNode of graph[node]) {34
if (visited.has(nextNode)) {35
dp[node] = dp[nextNode] + (n - 2);39
if (node !== 0 && totalChildren[node]) dp[node] -= totalChildren[node] * 2;40
for (let nextNode of graph[node]) {41
if (visited.has(nextNode)) continue;42
else findDistance(nextNode);