Advertisement
Iam_Sandeep

834. Sum of Distances in Tree

Aug 1st, 2022
1,074
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 KB | None | 0 0
  1. '''
  2. There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
  3. You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
  4. Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.
  5. '''
  6. #Since it is tree we dont need visited array just one variable parent is enough
  7. #Question follows root shifting technique
  8. #sum[child]=sum[parent]-count[child]+n-count[child]
  9. #It means when you shift root to a child then count[child] nodes move towards the root by '1' and n-count[child] moves away by '1'
  10. class Solution:
  11.     def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
  12.         count=[1]*n  #We initialised all counts with 1 means counting itself as 1. We can remove here 1 and while caluculating count of every node there you can add 1
  13.         ans=[0]*n #In this array we store sum of distances from node to node
  14.         g=defaultdict(set)
  15.         for u,v in edges:
  16.             g[u].add(v)
  17.             g[v].add(u)
  18.            
  19.         def dfs(node=0,parent=-1): #This traversal helps in building count array and also sum of all distances from 0 to every other node and every other node to root
  20.             for child in g[node]:
  21.                 if child!=parent: #If its not visited
  22.                     dfs(child,node)
  23.                     count[node]+=count[child]
  24.                     ans[node]+=ans[child]+count[child] #sum[p]=count[c]+sum[c] for every child. This you can generalise
  25.        
  26.         def dfs1(node=0,parent=-1): # This traversal helps in root shifting technique and caluculate all requires sums
  27.             for c in g[node]:
  28.                 if c!=parent:
  29.                     ans[c]=ans[node]-count[c]+n-count[c]
  30.                     dfs1(c,node)
  31.        
  32.         dfs()
  33.         dfs1()
  34.         return ans
  35.            
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement