Maximum value at each level in an N | C # program for the above approach ; 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
using System ; using System . Collections . Generic ; class GFG { static void maxAtLevel ( int N , int M , int [ ] Value , int [ , ] Edges ) { List < int > [ ] adj = new List < int > [ N ] ; for ( int i = 0 ; i < adj . Length ; i ++ ) adj [ i ] = new List < int > ( ) ; for ( int i = 0 ; i < M ; i ++ ) { int u = Edges [ i , 0 ] ; int v = Edges [ i , 1 ] ; adj [ u ] . Add ( v ) ; } Queue < int > q = new Queue < int > ( ) ; q . Enqueue ( 0 ) ; while ( q . Count != 0 ) { int count = q . Count ; int maxVal = 0 ; while ( count -- > 0 ) { int temp = q . Peek ( ) ; q . Dequeue ( ) ; maxVal = Math . Max ( maxVal , Value [ temp ] ) ; for ( int i = 0 ; i < adj [ temp ] . Count ; i ++ ) { q . Enqueue ( adj [ temp ] [ i ] ) ; } } Console . Write ( maxVal + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int N = 10 ; int [ , ] Edges = { { 0 , 1 } , { 0 , 2 } , { 0 , 3 } , { 1 , 4 } , { 1 , 5 } , { 3 , 6 } , { 6 , 7 } , { 6 , 8 } , { 6 , 9 } } ; int [ ] Value = { 1 , 2 , - 1 , 3 , 4 , 5 , 8 , 6 , 12 , 7 } ; maxAtLevel ( N , N - 1 , Value , Edges ) ; } }