Maximum level sum in N-ary Tree
Last Updated :
06 Jun, 2022
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++
#include <bits/stdc++.h>
using namespace std;
int maxLevelSum( int N, int M,
vector< int > Value,
int Edges[][2])
{
vector< int > adj[N];
for ( int i = 0; i < M; i++) {
adj[Edges[i][0]].push_back(
Edges[i][1]);
}
int result = Value[0];
queue< int > q;
q.push(0);
while (!q.empty()) {
int count = q.size();
int sum = 0;
while (count--) {
int temp = q.front();
q.pop();
sum = sum + Value[temp];
for ( int i = 0;
i < adj[temp].size(); i++) {
q.push(adj[temp][i]);
}
}
result = max(sum, result);
}
return result;
}
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 };
cout << maxLevelSum(N, N - 1,
Value, Edges);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
class GFG{
@SuppressWarnings ( "unchecked" )
static int maxLevelSum( int N, int M, int [] Value,
int Edges[][])
{
ArrayList<Integer>[] adj = new ArrayList[N];
for ( int i = 0 ; i < N; i++)
{
adj[i] = new ArrayList<>();
}
for ( int i = 0 ; i < M; i++)
{
adj[Edges[i][ 0 ]].add(Edges[i][ 1 ]);
}
int result = Value[ 0 ];
Queue<Integer> q = new LinkedList<>();
q.add( 0 );
while (!q.isEmpty())
{
int count = q.size();
int sum = 0 ;
while (count-- > 0 )
{
int temp = q.poll();
sum = sum + Value[temp];
for ( int i = 0 ; i < adj[temp].size(); i++)
{
q.add(adj[temp].get(i));
}
}
result = Math.max(sum, result);
}
return result;
}
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 };
System.out.println(maxLevelSum(N, N - 1 ,
Value, Edges));
}
}
|
Python3
from collections import deque
def maxLevelSum(N, M, Value, Edges):
adj = [[] for i in range (N)]
for i in range (M):
adj[Edges[i][ 0 ]].append(Edges[i][ 1 ])
result = Value[ 0 ]
q = deque()
q.append( 0 )
while ( len (q) > 0 ):
count = len (q)
sum = 0
while (count):
temp = q.popleft()
sum = sum + Value[temp]
for i in range ( len (adj[temp])):
q.append(adj[temp][i])
count - = 1
result = max ( sum , result)
return result
if __name__ = = '__main__' :
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 ]
print (maxLevelSum(N, N - 1 ,
Value, Edges))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int maxLevelSum( int N, int M,
int [] Value,
int [,]Edges)
{
List< int >[] adj = new List< int >[N];
for ( int i = 0; i < N; i++)
{
adj[i] = new List< int >();
}
for ( int i = 0; i < M; i++)
{
adj[Edges[i, 0]].Add(Edges[i, 1]);
}
int result = Value[0];
Queue< int > q = new Queue< int >();
q.Enqueue(0);
while (q.Count != 0)
{
int count = q.Count;
int sum = 0;
while (count-- > 0)
{
int temp = q.Peek();
q.Dequeue();
sum = sum + Value[temp];
for ( int i = 0;
i < adj[temp].Count; i++)
{
q.Enqueue(adj[temp][i]);
}
}
result = Math.Max(sum, result);
}
return result;
}
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};
Console.WriteLine(maxLevelSum(N, N - 1,
Value, Edges));
}
}
|
Javascript
<script>
function maxLevelSum(N, M, Value, Edges)
{
let adj = new Array(N);
for (let i = 0; i < N; i++)
{
adj[i] = [];
}
for (let i = 0; i < M; i++)
{
adj[Edges[i][0]].push(Edges[i][1]);
}
let result = Value[0];
let q = [];
q.push(0);
while (q.length != 0)
{
let count = q.length;
let sum = 0;
while (count-- > 0)
{
let temp = q[0];
q.shift();
sum = sum + Value[temp];
for (let i = 0; i < adj[temp].length; i++)
{
q.push(adj[temp][i]);
}
}
result = Math.max(sum, result);
}
return result;
}
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];
document.write(maxLevelSum(N, N - 1, Value, Edges));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...