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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxAtLevel ( int N , int M , vector < int > Value , int Edges [ ] [ 2 ] ) { vector < int > adj [ N ] ; for ( int i = 0 ; i < M ; i ++ ) { int u = Edges [ i ] [ 0 ] ; int v = Edges [ i ] [ 1 ] ; adj [ u ] . push_back ( v ) ; } queue < int > q ; q . push ( 0 ) ; while ( ! q . empty ( ) ) { int count = q . size ( ) ; int maxVal = 0 ; while ( count -- ) { int temp = q . front ( ) ; q . pop ( ) ; maxVal = max ( maxVal , Value [ temp ] ) ; for ( int i = 0 ; i < adj [ temp ] . size ( ) ; i ++ ) { q . push ( adj [ temp ] [ i ] ) ; } } cout << maxVal << " ▁ " ; } } int main ( ) { int N = 10 ; int Edges [ ] [ 2 ] = { { 0 , 1 } , { 0 , 2 } , { 0 , 3 } , { 1 , 4 } , { 1 , 5 } , { 3 , 6 } , { 6 , 7 } , { 6 , 8 } , { 6 , 9 } } ; vector < int > Value = { 1 , 2 , -1 , 3 , 4 , 5 , 8 , 6 , 12 , 7 } ; maxAtLevel ( N , N - 1 , Value , Edges ) ; return 0 ; }