Kali_prasad

endpoints of tree diameter

Aug 31st, 2025
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.25 KB | None | 0 0
  1. '''
  2. given you count of treeNodes and the edges
  3. mark the endpoint nodes, which are part of diameter
  4.  
  5. '''
  6.  
  7. class Solution:
  8.  
  9.     def calculateddp(self,ddp,root,treeMap):
  10.         if root not in treeMap:
  11.             ddp[root] = 1
  12.             return
  13.         maxDown = 0
  14.         for c in treeMap[root]:
  15.             self.calculateddp(ddp,c,treeMap)
  16.             maxDown = max(maxDown,ddp[c])
  17.         ddp[root] = 1 + maxDown
  18.         return
  19.  
  20.  
  21.     def endPointsOfTreeDiameter(self,nodes,nodeFrom,nodeTo):
  22.         treeMap = {}
  23.         parentMap = {}
  24.         edgesLen = len(nodeFrom)
  25.         for i in range(edgesLen):
  26.             if nodeFrom[i] in treeMap:
  27.                 treeMap[nodeFrom[i]].append(nodeTo[i])
  28.             else:
  29.                 treeMap[nodeFrom[i]] = [nodeTo[i]]
  30.             parentMap[nodeTo[i]] = nodeFrom[i]
  31.            
  32.         root = 1 #assuming root to be 1
  33.         for i in range(1,nodes+1):
  34.             if i not in nodeTo:
  35.                 root = i
  36.                 break
  37.         #calculate downward maxlen dp for every node
  38.         ddp = [0 for _ in range(nodes+1)]
  39.         self.calculateddp(ddp,root,treeMap)
  40.  
  41.         #calculate upward dp as max(curr + parent + sibling downward dp's) #curr is 1 , parent is 1 if exist
  42.         udp = [0 for _ in range(nodes+1)]
  43.  
  44.         parent = None
  45.         q = []
  46.         q.extend(treeMap[root]) #you cannot attach treeMap[parent] otherwise
  47.         udp[root] = 1
  48.         while len(q):
  49.             curr = q.pop(0)
  50.             parent = parentMap[curr]#getting the parent for curr
  51.             # print(f"treeMap[parent] {treeMap[parent]}")
  52.             # print(f"parent is {parent} treeMap[parent] is {treeMap[parent]}")
  53.             siblings = [x for x in treeMap[parent] if x!=curr]
  54.             # print(f"curr is {curr} siblings {siblings}")
  55.             siblingsddp = [ddp[x] for x in siblings]
  56.             # print(f"curr is {curr} siblingsddp is {siblingsddp}")
  57.             maxsiblingddp = max(siblingsddp) if len(siblingsddp) else 0
  58.             udp[curr] = 1+max(1+maxsiblingddp,udp[parent])#(1stroke up and then downward direction) vs (udp of parent)
  59.             if len(treeMap.get(curr,[])):
  60.                 q.extend(treeMap[curr])#imp
  61.        
  62.         # maxi = max(udp) #getting the diameter
  63.         # print(f"ddp is {ddp}")
  64.  
  65.         # print(f"udp is {udp}")
  66.         # print(f"maxi is {maxi}")
  67.         maxdiams = [0 for _ in range(nodes+1)]
  68.         ans = [0 for _ in range(nodes+1)]
  69.         for i in range(len(maxdiams)):
  70.             maxdiams[i] = max(udp[i],ddp[i])#either one length can you give you max path ,so even if root is endpoint we can handle
  71.         maxi = max(maxdiams)
  72.         for i in range(len(maxdiams)):
  73.             if maxi == maxdiams[i]:
  74.                 ans[i] = 1
  75.  
  76.  
  77.         if udp[root]+ddp[root]-1 == maxi:
  78.             ans[root] = 1
  79.         return ans[1:]
  80.        
  81.  
  82.  
  83. def run_tests():
  84.     sol = Solution()
  85.     cases = [
  86.         (7, [1,2,3,3,1,1], [2,3,4,5,6,7]),
  87.         (9, [1,2,8,3,3,1,1,8], [2,8,3,4,5,6,7,9]),
  88.         (2, [2], [1]),
  89.         (5, [1,1,2,2], [2,3,4,5]),
  90.         (3, [1,2], [2,3]),
  91.         (4, [1,2,2], [2,3,4])
  92.     ]
  93.    
  94.     for case in cases:
  95.         print(sol.endPointsOfTreeDiameter(*case))
  96.    
  97.  
  98. if __name__ == "__main__":
  99.     run_tests()
  100.  
Advertisement
Add Comment
Please, Sign In to add comment