Maximum value at each level in an N | Function to find the maximum value at each level of N - ary tree ; Stores the adjacency list ; Create the adjacency list ; Perform level order traversal of nodes at each level ; Push the root node ; Iterate until queue is empty ; Get the size of queue ; Iterate for : all the nodes in the queue currently ; Dequeue an node from queue ; Enqueue the children of dequeued node ; Print the result ; Driver Code ; Number of nodes ; Edges of the N - ary tree ; Given cost ; Function Call
def maxAtLevel ( N , M , Value , 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 q = [ ] NEW_LINE q . append ( 0 ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT count = len ( q ) NEW_LINE maxVal = 0 NEW_LINE while ( count ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . remove ( q [ 0 ] ) NEW_LINE maxVal = max ( maxVal , Value [ temp ] ) NEW_LINE for i in range ( len ( adj [ temp ] ) ) : NEW_LINE INDENT q . append ( adj [ temp ] [ i ] ) NEW_LINE DEDENT count -= 1 NEW_LINE DEDENT print ( maxVal , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE Edges = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 0 , 3 ] , [ 1 , 4 ] , [ 1 , 5 ] , [ 3 , 6 ] , [ 6 , 7 ] , [ 6 , 8 ] , [ 6 , 9 ] ] NEW_LINE Value = [ 1 , 2 , - 1 , 3 , 4 , 5 , 8 , 6 , 12 , 7 ] NEW_LINE maxAtLevel ( N , N - 1 , Value , Edges ) NEW_LINE DEDENT