# Maximum level sum in N-ary Tree

Given an N-ary Tree consisting of nodes valued [1, N] and an array value[], where each node i is associated with value[i], the task is to find the maximum of sum of all node values of all levels of the N-ary Tree.

Examples:

Input: N = 8, Edges[] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}}, Value[] = {4, 2, 3, -5, -1, 3, -2, 6}
Output: 6
Explanation:
Sum of all nodes of 0th level is 4
Sum of all nodes of 1st level is 0
Sum of all the nodes of 3rd level is 0.
Sum of all the odes of 4th level is 6.
Therefore, maximum sum of any level of the tree is 6.

Input: N = 10, Edges[] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}, {6, 8}, {6, 9}}, Value[] = {1, 2, -1, 3, 4, 5, 8, 6, 12, 7}
Output: 25

Approach: This problem can be solved using Level order Traversal. While performing the traversal, process nodes of different levels separately. For every level being processed, compute the sum of nodes at that level and keep track of the maximum sum. Follow the steps:

1. Store all the child nodes at the current level in the queue and then count the total sum of nodes at the current level after the level order traversal for a particular level is completed.
2. Since the queue now contains all the nodes of the next level, the total sum of nodes in the next level can be easily calculated by traversing the queue.
3. Follow the same procedure for the successive levels and update the maximum sum of nodes found at each level.
4. After the above steps, print the maximum sum of values stored.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach`   `#include ` `using` `namespace` `std;`   `// Function to find the maximum sum` `// a level in N-ary treeusing BFS` `int` `maxLevelSum(``int` `N, ``int` `M,` `                ``vector<``int``> Value,` `                ``int` `Edges[])` `{` `    ``// Stores the edges of the graph` `    ``vector<``int``> adj[N];`   `    ``// Create Adjacency list` `    ``for` `(``int` `i = 0; i < M; i++) {` `        ``adj[Edges[i]].push_back(` `            ``Edges[i]);` `    ``}`   `    ``// Initialize result` `    ``int` `result = Value;`   `    ``// Stores the nodes of each level` `    ``queue<``int``> q;`   `    ``// Insert root` `    ``q.push(0);`   `    ``// Perform level order traversal` `    ``while` `(!q.empty()) {`   `        ``// Count of nodes of the` `        ``// current level` `        ``int` `count = q.size();`   `        ``int` `sum = 0;`   `        ``// Traverse the current level` `        ``while` `(count--) {`   `            ``// Dequeue a node from queue` `            ``int` `temp = q.front();` `            ``q.pop();`   `            ``// Update sum of current level` `            ``sum = sum + Value[temp];`   `            ``// Enqueue the children of` `            ``// dequeued node` `            ``for` `(``int` `i = 0;` `                 ``i < adj[temp].size(); i++) {` `                ``q.push(adj[temp][i]);` `            ``}` `        ``}`   `        ``// Update maximum level sum` `        ``result = max(sum, result);` `    ``}`   `    ``// Return the result` `    ``return` `result;` `}`   `// Driver Code` `int` `main()` `{` `    ``// Number of nodes` `    ``int` `N = 10;`   `    ``// Edges of the N-ary tree` `    ``int` `Edges[] = { { 0, 1 }, { 0, 2 },` `                       ``{ 0, 3 }, { 1, 4 },` `                       ``{ 1, 5 }, { 3, 6 },` `                       ``{ 6, 7 }, { 6, 8 },` `                       ``{ 6, 9 } };` `    ``// Given cost` `    ``vector<``int``> Value = { 1, 2, -1, 3, 4,` `                          ``5, 8, 6, 12, 7 };`   `    ``// Function call` `    ``cout << maxLevelSum(N, N - 1,` `                        ``Value, Edges);`   `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `import` `java.util.ArrayList;` `import` `java.util.LinkedList;` `import` `java.util.Queue;`   `class` `GFG{`   `// Function to find the maximum sum` `// a level in N-ary treeusing BFS` `@SuppressWarnings``(``"unchecked"``)` `static` `int` `maxLevelSum(``int` `N, ``int` `M, ``int``[] Value, ` `                                     ``int` `Edges[][])` `{` `    `  `    ``// Stores the edges of the graph` `    ``ArrayList[] adj = ``new` `ArrayList[N];`   `    ``for``(``int` `i = ``0``; i < N; i++)` `    ``{` `        ``adj[i] = ``new` `ArrayList<>();` `    ``}`   `    ``// Create Adjacency list` `    ``for``(``int` `i = ``0``; i < M; i++)` `    ``{` `        ``adj[Edges[i][``0``]].add(Edges[i][``1``]);` `    ``}`   `    ``// Initialize result` `    ``int` `result = Value[``0``];`   `    ``// Stores the nodes of each level` `    ``Queue q = ``new` `LinkedList<>();`   `    ``// Insert root` `    ``q.add(``0``);`   `    ``// Perform level order traversal` `    ``while` `(!q.isEmpty()) ` `    ``{` `        `  `        ``// Count of nodes of the` `        ``// current level` `        ``int` `count = q.size();`   `        ``int` `sum = ``0``;`   `        ``// Traverse the current level` `        ``while` `(count-- > ``0``) ` `        ``{` `            `  `            ``// Dequeue a node from queue` `            ``int` `temp = q.poll();`   `            ``// Update sum of current level` `            ``sum = sum + Value[temp];`   `            ``// Enqueue the children of` `            ``// dequeued node` `            ``for``(``int` `i = ``0``; i < adj[temp].size(); i++) ` `            ``{` `                ``q.add(adj[temp].get(i));` `            ``}` `        ``}`   `        ``// Update maximum level sum` `        ``result = Math.max(sum, result);` `    ``}`   `    ``// Return the result` `    ``return` `result;` `}`   `// Driver Code` `public` `static` `void` `main(String[] args) ` `{` `    `  `    ``// Number of nodes` `    ``int` `N = ``10``;`   `    ``// Edges of the N-ary tree` `    ``int``[][] Edges = { { ``0``, ``1` `}, { ``0``, ``2` `},` `                      ``{ ``0``, ``3` `}, { ``1``, ``4` `},` `                      ``{ ``1``, ``5` `}, { ``3``, ``6` `}, ` `                      ``{ ``6``, ``7` `}, { ``6``, ``8` `}, ` `                      ``{ ``6``, ``9` `} };` `    ``// Given cost` `    ``int``[] Value = { ``1``, ``2``, -``1``, ``3``, ``4``,` `                    ``5``, ``8``, ``6``, ``12``, ``7` `};`   `    ``// Function call` `    ``System.out.println(maxLevelSum(N, N - ``1``,` `                                   ``Value, Edges));` `}` `}`   `// This code is contributed by sanjeev2552`

## Python3

 `# Python3 program for the above approach` `from` `collections ``import` `deque`   `# Function to find the maximum sum` `# a level in N-ary treeusing BFS` `def` `maxLevelSum(N, M, Value, Edges):` `    `  `    ``# Stores the edges of the graph` `    ``adj ``=` `[[] ``for` `i ``in` `range``(N)]`   `    ``# Create Adjacency list` `    ``for` `i ``in` `range``(M):` `        ``adj[Edges[i][``0``]].append(Edges[i][``1``])`   `    ``# Initialize result` `    ``result ``=` `Value[``0``]`   `    ``# Stores the nodes of each level` `    ``q ``=` `deque()`   `    ``# Insert root` `    ``q.append(``0``)`   `    ``# Perform level order traversal` `    ``while` `(``len``(q) > ``0``):`   `        ``# Count of nodes of the` `        ``# current level` `        ``count ``=` `len``(q)`   `        ``sum` `=` `0`   `        ``# Traverse the current level` `        ``while` `(count):`   `            ``# Dequeue a node from queue` `            ``temp ``=` `q.popleft()`   `            ``# Update sum of current level` `            ``sum` `=` `sum` `+` `Value[temp]`   `            ``# Enqueue the children of` `            ``# dequeued node` `            ``for` `i ``in` `range``(``len``(adj[temp])):` `                ``q.append(adj[temp][i])` `                `  `            ``count ``-``=` `1`   `        ``# Update maximum level sum` `        ``result ``=` `max``(``sum``, result)`   `    ``# Return the result` `    ``return` `result`   `# Driver Code` `if` `__name__ ``=``=` `'__main__'``:` `    `  `    ``# Number of nodes` `    ``N ``=` `10`   `    ``# Edges of the N-ary tree` `    ``Edges ``=` `[ [ ``0``, ``1` `], [ ``0``, ``2` `],` `              ``[ ``0``, ``3` `], [ ``1``, ``4` `],` `              ``[ ``1``, ``5` `], [ ``3``, ``6` `],` `              ``[ ``6``, ``7` `], [ ``6``, ``8` `],` `              ``[ ``6``, ``9` `] ]` `              `  `    ``# Given cost` `    ``Value ``=` `[ ``1``, ``2``, ``-``1``, ``3``, ``4``, ` `              ``5``, ``8``, ``6``, ``12``, ``7` `]`   `    ``# Function call` `    ``print``(maxLevelSum(N, N ``-` `1``, ` `                      ``Value, Edges))`   `# This code is contributed by mohit kumar 29`

Output:

```25

```

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.