Maximum absolute difference between any two level sum in a N | Python3 program for the above approach ; Function to find the maximum absolute difference of level sum ; Create the adjacency list ; Initialize value of maximum and minimum level sum ; Do Level order traversal keeping track of nodes at every level ; Get the size of queue when the level order traversal for one level finishes ; Iterate for all the nodes in the queue currently ; Dequeue an node from queue ; Enqueue the children of dequeued node ; Update the maximum level sum value ; Update the minimum level sum value ; Return the result ; Driver Code ; Number of nodes and edges ; Edges of the N - ary tree ; Given cost ; Function call
from collections import deque NEW_LINE def maxAbsDiffLevelSum ( N , M , cost , Edges ) : NEW_LINE INDENT adj = [ [ ] for i in range ( N ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT u = Edges [ i ] [ 0 ] NEW_LINE v = Edges [ i ] [ 1 ] NEW_LINE adj [ u ] . append ( v ) NEW_LINE DEDENT maxSum = cost [ 0 ] NEW_LINE minSum = cost [ 0 ] NEW_LINE q = deque ( ) NEW_LINE q . append ( 0 ) NEW_LINE while len ( q ) > 0 : NEW_LINE INDENT count = len ( q ) NEW_LINE sum = 0 NEW_LINE while ( count ) : NEW_LINE INDENT temp = q . popleft ( ) NEW_LINE q . pop ( ) NEW_LINE sum = sum + cost [ temp ] NEW_LINE for i in adj [ temp ] : NEW_LINE INDENT q . append ( i ) NEW_LINE DEDENT count -= 1 NEW_LINE DEDENT maxSum = max ( sum , maxSum ) NEW_LINE minSum = min ( sum , minSum ) NEW_LINE DEDENT print ( abs ( maxSum - minSum ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE M = 9 NEW_LINE Edges = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 0 , 3 ] , [ 1 , 4 ] , [ 1 , 5 ] , [ 3 , 6 ] , [ 6 , 7 ] , [ 6 , 8 ] , [ 6 , 9 ] ] NEW_LINE cost = [ 1 , 2 , - 1 , 3 , 4 , 5 , 8 , 6 , 12 , 7 ] NEW_LINE maxAbsDiffLevelSum ( N , M , cost , Edges ) NEW_LINE DEDENT