varsumOfDistancesInTree=function(n,edges){constadjList=Array.from({length:n},()=>[])constcount=Array(n).fill(1)constres=Array(n).fill(0)constseen=newSet()for(const[u,v]ofedges){adjList[u].push(v)adjList[v].push(u)}functiondfs(node,parent){seen.add(node)for(constchildofadjList[node]){if(!seen.has(child)){dfs(child,node)count[node]+=count[child]res[node]+=res[child]+count[child]}}seen.delete(node)}functiondfs2(node,parent){seen.add(node)for(constchildofadjList[node]){if(!seen.has(child)){res[child]=res[node]-count[child]+(n-count[child])dfs2(child,node)}}seen.delete(node)}dfs(0,-1)dfs2(0,-1)returnres};
This could pass for a medium problem. I understood like 70% of it.
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse