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 ; Number of nodes ; Edges of the N - ary tree ; Given cost ; Function Call
function maxAtLevel ( N , M , Value , Edges ) { let adj = new Array ( N ) ; for ( let i = 0 ; i < adj . length ; i ++ ) adj [ i ] = [ ] ; for ( let i = 0 ; i < M ; i ++ ) { let u = Edges [ i ] [ 0 ] ; let v = Edges [ i ] [ 1 ] ; adj [ u ] . push ( v ) ; } let q = [ ] ; q . push ( 0 ) ; while ( q . length > 0 ) { let count = q . length ; let maxVal = 0 ; while ( count -- > 0 ) { let temp = q [ 0 ] ; q . shift ( ) ; maxVal = Math . max ( maxVal , Value [ temp ] ) ; for ( let i = 0 ; i < adj [ temp ] . length ; i ++ ) { q . push ( adj [ temp ] [ i ] ) ; } } document . write ( maxVal + " " ) ; } } let N = 10 ; let Edges = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 0 , 3 ] , [ 1 , 4 ] , [ 1 , 5 ] , [ 3 , 6 ] , [ 6 , 7 ] , [ 6 , 8 ] , [ 6 , 9 ] ] ; let Value = [ 1 , 2 , - 1 , 3 , 4 , 5 , 8 , 6 , 12 , 7 ] ; maxAtLevel ( N , N - 1 , Value , Edges ) ;