classSolution{public:vector<int>sumOfDistancesInTree(intN,vector<vector<int>>&edges){vector<int>ans(N);vector<int>count(N,1);vector<unordered_set<int>>tree(N);for(constvector<int>&e:edges){constintu=e[0];constintv=e[1];tree[u].insert(v);tree[v].insert(u);}postorder(tree,0,-1,count,ans);preorder(tree,0,-1,count,ans);returnans;}private:voidpostorder(constvector<unordered_set<int>>&tree,intnode,intparent,vector<int>&count,vector<int>&ans){for(constintchild:tree[node]){if(child==parent)continue;postorder(tree,child,node,count,ans);count[node]+=count[child];ans[node]+=ans[child]+count[child];}}voidpreorder(constvector<unordered_set<int>>&tree,intnode,intparent,vector<int>&count,vector<int>&ans){for(constintchild:tree[node]){if(child==parent)continue;// count[child] nodes are 1 step closer from child than parent// (N - count[child]) nodes are 1 step farther from child than parentans[child]=ans[node]-count[child]+(tree.size()-count[child]);preorder(tree,child,node,count,ans);}}};
classSolution{publicint[]sumOfDistancesInTree(intN,int[][]edges){int[]ans=newint[N];int[]count=newint[N];Set<Integer>[]tree=newSet[N];Arrays.fill(count,1);for(inti=0;i<N;++i)tree[i]=newHashSet<>();for(int[]e:edges){finalintu=e[0];finalintv=e[1];tree[u].add(v);tree[v].add(u);}postorder(tree,0,-1,count,ans);preorder(tree,0,-1,count,ans);returnans;}privatevoidpostorder(Set<Integer>[]tree,intnode,intparent,int[]count,int[]ans){for(finalintchild:tree[node]){if(child==parent)continue;postorder(tree,child,node,count,ans);count[node]+=count[child];ans[node]+=ans[child]+count[child];}}privatevoidpreorder(Set<Integer>[]tree,intnode,intparent,int[]count,int[]ans){for(finalintchild:tree[node]){if(child==parent)continue;// count[child] nodes are 1 step closer from child than parent// (N - count[child]) nodes are 1 step farther from child than parentans[child]=ans[node]-count[child]+(tree.length-count[child]);preorder(tree,child,node,count,ans);}}}
classSolution:defsumOfDistancesInTree(self,N:int,edges:List[List[int]])->List[int]:ans=[0]*Ncount=[1]*Ntree=defaultdict(set)foru,vinedges:tree[u].add(v)tree[v].add(u)defpostorder(node,parent=None):forchildintree[node]:ifchild==parent:continuepostorder(child,node)count[node]+=count[child]ans[node]+=ans[child]+count[child]defpreorder(node,parent=None):forchildintree[node]:ifchild==parent:continue# count[child] nodes are 1 step closer from child than parent# (N - count[child]) nodes are 1 step farther from child than parentans[child]=ans[node]-count[child]+(N-count[child])preorder(child,node)postorder(0)preorder(0)returnans