![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
25
Time Complexity: O(N)
Auxiliary Space: O(N)