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[][2] = {{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 nodes of 4th level is 6.Â
Therefore, maximum sum of any level of the tree is 6.Input: N = 10, Edges[][2] = {{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:
- 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.
- 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.
- Follow the same procedure for the successive levels and update the maximum sum of nodes found at each level.
- 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 <bits/stdc++.h>using namespace std;Â
// Function to find the maximum sum// a level in N-ary treeusing BFSint maxLevelSum(int N, int M,                vector<int> Value,                int Edges[][2]){    // Stores the edges of the graph    vector<int> adj[N];Â
    // Create Adjacency list    for (int i = 0; i < M; i++) {        adj[Edges[i][0]].push_back(            Edges[i][1]);    }Â
    // Initialize result    int result = Value[0];Â
    // 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 Codeint main(){    // Number of nodes    int N = 10;Â
    // Edges of the N-ary tree    int Edges[][2] = { { 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 approachimport 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<Integer>[] 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<Integer> 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 Codepublic 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 approachfrom collections import dequeÂ
# Function to find the maximum sum# a level in N-ary treeusing BFSdef 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 Codeif __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 |
C#
// C# program for the // above approachusing System;using System.Collections.Generic;class GFG{Â
// Function to find the maximum sum// a level in N-ary treeusing BFSÂ
static int maxLevelSum(int N, int M,                        int[] Value,                        int [,]Edges){  // Stores the edges of the graph  List<int>[] adj = new List<int>[N];Â
  for(int i = 0; i < N; i++)  {    adj[i] = new List<int>();  }Â
  // 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<int> q = new Queue<int>();Â
  // Insert root  q.Enqueue(0);Â
  // Perform level order   // traversal  while (q.Count != 0)   {    // Count of nodes of the    // current level    int count = q.Count;Â
    int sum = 0;Â
    // Traverse the current     // level    while (count-- > 0)     {      // Dequeue a node from       // queue      int temp = q.Peek();      q.Dequeue();Â
      // Update sum of current       // level      sum = sum + Value[temp];Â
      // Enqueue the children of      // dequeued node      for(int i = 0;               i < adj[temp].Count; i++)       {        q.Enqueue(adj[temp][i]);      }    }Â
    // Update maximum level sum    result = Math.Max(sum, result);  }Â
  // Return the result  return result;}Â
// Driver Codepublic 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  Console.WriteLine(maxLevelSum(N, N - 1,                                Value, Edges));}}Â
// This code is contributed by Princi Singh |
Javascript
<script>Â
    // JavaScript program for the above approach         // Function to find the maximum sum    // a level in N-ary treeusing BFSÂ
    function maxLevelSum(N, M, Value, Edges)    {      // Stores the edges of the graph      let adj = new Array(N);Â
      for(let i = 0; i < N; i++)      {        adj[i] = [];      }Â
      // Create Adjacency list      for(let i = 0; i < M; i++)      {        adj[Edges[i][0]].push(Edges[i][1]);      }Â
      // Initialize result      let result = Value[0];Â
      // Stores the nodes of each level      let q = [];Â
      // Insert root      q.push(0);Â
      // Perform level order      // traversal      while (q.length != 0)      {        // Count of nodes of the        // current level        let count = q.length;Â
        let sum = 0;Â
        // Traverse the current        // level        while (count-- > 0)        {          // Dequeue a node from          // queue          let temp = q[0];          q.shift();Â
          // Update sum of current          // level          sum = sum + Value[temp];Â
          // Enqueue the children of          // dequeued node          for(let i = 0; i < adj[temp].length; i++)          {            q.push(adj[temp][i]);          }        }Â
        // Update maximum level sum        result = Math.max(sum, result);      }Â
      // Return the result      return result;    }         // Number of nodes    let N = 10;Â
    // Edges of the N-ary tree    let Edges = [[0, 1], [0, 2],                    [0, 3], [1, 4],                    [1, 5], [3, 6],                    [6, 7], [6, 8],                    [6, 9]];    // Given cost    let Value = [1, 2, -1, 3, 4, 5, 8, 6, 12, 7];Â
    // Function call    document.write(maxLevelSum(N, N - 1, Value, Edges));Â
</script> |
25
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Information on that Topic: geeksforgeeks.org/maximum-level-sum-in-n-ary-tree/ […]