The Wayback Machine - https://web.archive.org/web/20210205152720/https://www.geeksforgeeks.org/calculate-sum-of-all-nodes-present-in-a-level-for-each-level-of-a-tree/
Skip to content
Related Articles

Related Articles

Calculate sum of all nodes present in a level for each level of a Tree
  • Last Updated : 05 Feb, 2021

Given a Generic Tree consisting of N nodes (rooted at 0) where each node is associated with a value, the task for each level of the Tree is to find the sum of all node values present at that level of the tree.

Examples:

Input: node_number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, node_values = { 2, 3, 4, 4, 7, 6, 2, 3, 9, 1 }

Output:
Sum of level 0 = 2
Sum of level 1 = 7
Sum of level 2 = 14
Sum of level 3 = 18
Explanation :



  • Nodes on level 0 = {1} with value is 2
  • Nodes on level 1 = {2, 3} and their respective values are {3, 4}. Sum = 7.
  • Nodes on level 2 = {4, 5, 8} with values {4, 7, 3} respectively. Sum = 14.
  • Nodes on level 3 = {6, 7, 9, 10} with values {6, 2, 9, 1} respectively. Sum = 18

Input: node_number = { 1 }, node_values = { 10 }
Output: Sum of level 0 = 10

Approach: Follow the steps below to solve the problem:

  1. Traverse the tree using DFS or BFS
  2. Store the level of this node using this approach.
  3. Then, add the node values to the corresponding level of the node in an array, say sum[ ].
  4. Print the array sum[] showing the sum of all nodes on each level.

Below is the implementation of the above approach :

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to add edges to the tree
void add_edge(int a, int b,
              vector<vector<int> >& tree)
{
    // 0-based indexing
    a--, b--;
  
    tree[a].push_back(b);
    tree[b].push_back(a);
}
  
// Function to print sum of
// nodes on all levels of a tree
void dfs(int u, int level, int par,
         int node_values[], vector<vector<int> >& tree,
         map<int, int>& sum, int& depth)
{
    // update max depth of tree
    depth = max(depth, level);
  
    // Add value of current node
    // to its corresponding level
    sum[level] += node_values[u];
  
    for (int child : tree[u]) {
  
        if (child == par)
            continue;
  
        // Recursive traverse child nodes
        dfs(child, level + 1, u, node_values,
            tree, sum, depth);
    }
}
  
// Function to calculate sum of
// nodes of each level of the Tree
void getSum(int node_values[],
            vector<vector<int> >& tree)
{
    // Depth of the tree
    int depth = 0;
  
    // Stores sum at each level
    map<int, int> sum;
  
    dfs(0, 0,
        -1, node_values,
        tree, sum, depth);
  
    // Print final sum
    for (int i = 0; i <= depth; i++) {
        cout << "Sum of level " << i
             << " = " << sum[i] << endl;
    }
}
  
// Driver Code
int32_t main()
{
  
    // Create a tree structure
    int N = 10;
  
    vector<vector<int> > tree(N);
    add_edge(1, 2, tree);
    add_edge(1, 3, tree);
    add_edge(2, 4, tree);
    add_edge(3, 5, tree);
    add_edge(3, 8, tree);
    add_edge(5, 6, tree);
    add_edge(5, 7, tree);
    add_edge(8, 9, tree);
    add_edge(8, 10, tree);
  
    int node_values[]
        = { 2, 3, 4, 4, 7,
            6, 2, 3, 9, 1 };
  
    // Function call to get the sum
    // of nodes of different level
    getSum(node_values, tree);
  
    return 0;
}

chevron_right


Output:

Sum of level 0 = 2
Sum of level 1 = 7
Sum of level 2 = 14
Sum of level 3 = 18

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
Recommended Articles
Page :