VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-absolute-difference-between-any-two-level-sum-in-a-n-ary-tree/

⇱ Maximum absolute difference between any two level sum in a N-ary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum absolute difference between any two level sum in a N-ary Tree

Last Updated : 15 Jul, 2025

Given an N-ary Tree having N nodes with positive and negative values and (N - 1) edges, the task is to find the maximum absolute difference of level sum in it.

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}, Below is the graph: 
 

👁 Image


Output: 6
Explanation:
Sum of all nodes of 0th level is 4.
Sum of all nodes of 1st level is 0.
Sum of all nodes of 2nd level is 6.
Hence, maximum absolute difference of level sum = (6 – 0) = 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}, Below is the graph:

👁 Image


Output: 24

Approach: To find the maximum absolute difference of level sum, first find the maximum level sum and minimum level sum because the absolute difference of maximum level sum and minimum level sum always gives us maximum absolute difference i.e.,

Maximum absolute difference = abs(Maximum level sum - Minimum level sum)

Below are the steps:

  1. Perform the BFS Traversal on the given N-ary tree.
  2. While doing the BFS traversal, process nodes of different levels separately.
  3. For every level being processed, compute the sum of nodes in the level and keep track of maximum and minimum level sum.
  4. After the above traversal, find the absolute difference of maximum and minimum level sum.

Below is the implementation of the above approach:


Output: 
24

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

Comment
Article Tags: