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:
- Traverse the tree using DFS or BFS
- Store the level of this node using this approach.
- Then, add the node values to the corresponding level of the node in an array, say sum[ ].
- Print the array sum[] showing the sum of all nodes on each level.
Below is the implementation of the above approach :
C++
// C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to add edges to the treevoid 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 treevoid 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 Treevoid 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 Codeint32_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;} |
Java
// Java implementation of// the above approachimport java.io.*;import java.util.*;Â
class GFG{Â Â Â Â Â static Map<Integer, Integer> sum = new HashMap<>();static int depth = 0;Â
// Function to add edges to the treestatic void add_edge(int a, int b,                      ArrayList<ArrayList<Integer>> tree){         // 0-based indexing    a--;    b--;      tree.get(a).add(b);    tree.get(b).add(a);}  // Function to print sum of// Nodes on all levels of a treestatic void dfs(int u, int level, int par,                int []node_values,                 ArrayList<ArrayList<Integer>> tree){         // Update max depth of tree    depth = Math.max(depth, level);      // Add value of current node    // to its corresponding level    if (sum.containsKey(level))    {        sum.put(level, sum.get(level) +                        node_values[u]);    }    else        sum.put(level,node_values[u]);           for(int child : tree.get(u))    {        if (child == par)            continue;          // Recursive traverse child nodes        dfs(child, level + 1, u, node_values,            tree);    }}  // Function to calculate sum of// nodes of each level of the Treestatic void getSum(int []node_values,                    ArrayList<ArrayList<Integer>> tree){      dfs(0, 0, -1, node_values, tree);      // Print final sum    for(int i = 0; i <= depth; i++)     {        System.out.println("Sum of level " + (int) i +                                     " = " + sum.get(i));    }}  // Driver Codepublic static void main (String[] args) {         // Create a tree structure    int N = 10;      ArrayList<ArrayList<Integer>> tree = new ArrayList<ArrayList<Integer>>();    for(int i = 0; i < N; i++)       tree.add(new ArrayList<Integer>());            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);}}Â
// This code is contributed by avanitrachhadiya2155 |
Python3
# Python3 implementation of# the above approachÂ
# Function to add edges to the treedef add_edge(a, b):    global tree         # 0-based indexing    a, b = a - 1, b - 1    tree[a].append(b)    tree[b].append(a)Â
# Function to print sum of# nodes on all levels of a treedef dfs(u, level, par, node_values):    global sum, tree, depth         # update max depth of tree    depth = max(depth, level)Â
    # Add value of current node    # to its corresponding level    sum[level] = sum.get(level, 0) + node_values[u]    for child in tree[u]:        if (child == par):            continueÂ
        # Recursive traverse child nodes        dfs(child, level + 1, u, node_values)Â
# Function to calculate sum of# nodes of each level of the Treedef getSum(node_values):    global sum, depth, tree         # Depth of the tree    # depth = 0Â
    # Stores sum at each level    # map<int, int> sum    dfs(0, 0, -1, node_values)Â
    # Prfinal sum    for i in range(depth + 1):        print("Sum of level", i, "=", sum[i])Â
# Driver Codeif __name__ == '__main__':Â
    # Create a tree structure    N = 10    tree = [[] for i in range(N+1)]    sum = {}    depth = 0    add_edge(1, 2)    add_edge(1, 3)    add_edge(2, 4)    add_edge(3, 5)    add_edge(3, 8)    add_edge(5, 6)    add_edge(5, 7)    add_edge(8, 9)    add_edge(8, 10)    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)Â
    # This code is contributed by mohit kumar 29. |
C#
// C# implementation of// the above approachusing System;using System.Collections.Generic;class GFG{  static Dictionary<int, int> sum = new Dictionary<int,int>();  static int depth = 0;   // Function to add edges to the treestatic void add_edge(int a, int b, List<List<int>> tree){       // 0-based indexing    a--;    b--;Â
    tree[a].Add(b);    tree[b].Add(a);}Â
// Function to print sum of// Nodes on all levels of a treestatic void dfs(int u, int level, int par,         int []node_values, List<List<int>> tree         ){       // update max depth of tree    depth = Math.Max(depth, level);Â
    // Add value of current node    // to its corresponding level    if(sum.ContainsKey(level))      sum[level] += node_values[u];    else      sum[level] = node_values[u];Â
    foreach (int child in tree[u]) {Â
        if (child == par)            continue;Â
        // Recursive traverse child nodes        dfs(child, level + 1, u, node_values,            tree);    }}Â
// Function to calculate sum of// nodes of each level of the Treestatic void getSum(int []node_values, List<List<int>> tree){Â
    dfs(0, 0, -1, node_values, tree);Â
    // Print final sum    for (int i = 0; i <= depth; i++) {        Console.WriteLine("Sum of level " + (int) i + " = "+ sum[i]);    }}Â
// Driver Codepublic static void Main(){Â
    // Create a tree structure    int N = 10;Â
    List<List<int> > tree = new List<List<int>>();    for(int i = 0; i < N; i++)       tree.Add(new List<int>());    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);}}Â
// This code is contributed by bgangwar59. |
Javascript
<script>Â
// Javascript implementation of// the above approachvar sum = new Map();var depth = 0;   // Function to add edges to the treefunction add_edge(a, b, tree){         // 0-based indexing    a--;    b--;Â
    tree[a].push(b);    tree[b].push(a);}Â
// Function to print sum of// Nodes on all levels of a treefunction dfs(u, level, par, node_values, tree){         // Update max depth of tree    depth = Math.max(depth, level);Â
    // Push value of current node    // to its corresponding level    if (sum.has(level))        sum.set(level, sum.get(level) +                       node_values[u]);    else        sum.set(level, node_values[u])Â
    for(var child of tree[u])    {        if (child == par)            continue;Â
        // Recursive traverse child nodes        dfs(child, level + 1, u, node_values,            tree);    }}Â
// Function to calculate sum of// nodes of each level of the Treefunction getSum(node_values, tree){Â Â Â Â dfs(0, 0, -1, node_values, tree);Â
    // Print final sum    for(var i = 0; i <= depth; i++)     {        document.write("Sum of level " + i +                       " = "+ sum.get(i) + "<br>");    }}Â
// Driver CodeÂ
// Create a tree structurevar N = 10;var tree = [];for(var i = 0; i < N; i++)Â Â Â tree.push([]);Â Â Â Â 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);var node_values = [ 2, 3, 4, 4, 7,6, 2, 3, 9, 1 ];Â
// Function call to get the sum// of nodes of different levelgetSum(node_values, tree);Â
// This code is contributed by rrrtnxÂ
</script> |
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)
Iterative Approach(Level Order Traversal using Queue Data Structure):
Follow the below steps to solve the above problem:
1) Perform level Order Traversal and keep track of level and sum at each level.
2) At each level calculate sum and print sum along with level.
3) Repeat the step-2 at each level till last level.
Below is the implementation of above approach:
C++
// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL(KIRTIAGARWAL23121999)// C++ Implementation of above approach#include<bits/stdc++.h>using namespace std;Â
// a binary tree nodestruct Node{Â Â Â Â int data;Â Â Â Â Node *left, *right;Â Â Â Â Node(int data){Â Â Â Â Â Â Â Â this->data = data;Â Â Â Â Â Â Â Â this->left = this->right = NULL;Â Â Â Â }};Â
// a utility function to create a new nodeNode* newNode(int data){Â Â Â Â return new Node(data);}Â
void getSum(int node_values[], Node* root){Â Â Â Â queue<Node*> q;Â Â Â Â q.push(root);Â Â Â Â int level = 0;Â Â Â Â while(!q.empty()){Â Â Â Â Â Â Â Â int n = q.size();Â Â Â Â Â Â Â Â int sum = 0;Â Â Â Â Â Â Â Â for(int i = 0; i<n; i++){Â Â Â Â Â Â Â Â Â Â Â Â Node* front_node = q.front();Â Â Â Â Â Â Â Â Â Â Â Â q.pop();Â Â Â Â Â Â Â Â Â Â Â Â sum += node_values[front_node->data - 1];Â Â Â Â Â Â Â Â Â Â Â Â if(front_node->left) q.push(front_node->left);Â Â Â Â Â Â Â Â Â Â Â Â if(front_node->right) q.push(front_node->right);Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â cout<<"Sum of level "<<level<<" : "<<sum<<endl;Â Â Â Â Â Â Â Â level++;Â Â Â Â }}Â
// driver code to test above functionint main(){    Node* root = newNode(1);    root->left = newNode(2);    root->right = newNode(3);    root->left->left = newNode(4);    root->right->left = newNode(5);    root->right->right = newNode(8);    root->right->left->left = newNode(6);    root->right->left->right = newNode(7);    root->right->right->left = newNode(9);    root->right->right->right = newNode(10);         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, root);    return 0;} |
Java
import java.util.LinkedList;import java.util.Queue;Â
class Node {Â Â Â Â int data;Â Â Â Â Node left, right;Â
    public Node(int data)    {        this.data = data;        this.left = this.right = null;    }}Â
public class GFG {    public static void getSum(int[] node_values, Node root)    {               // Create a queue to store the nodes of the binary        // tree        Queue<Node> q = new LinkedList<>();               // Add the root node to the queue        q.add(root);               // Initialize the level to 0        int level = 0;               // Loop until the queue is empty        while (!q.isEmpty())         {                       // Get the number of nodes at the current level            int n = q.size();                       // Initialize the sum to 0            int sum = 0;                       // Loop through all the nodes at the current            // level            for (int i = 0; i < n; i++)             {                               // Get the front node from the queue                Node front_node = q.poll();                               // Add the value of the node to the sum                sum += node_values[front_node.data - 1];                               // Add the left child of the front node to                // the queue if it exists                if (front_node.left != null) {                    q.add(front_node.left);                }                               // Add the right child of the front node to                // the queue if it exists                if (front_node.right != null) {                    q.add(front_node.right);                }            }                       // Print the sum of the nodes at the current            // level            System.out.println("Sum of level " + level                               + " : " + sum);            // Increment the level            level++;        }    }Â
    public static void main(String[] args)    {        // Create the binary tree        Node root = new Node(1);        root.left = new Node(2);        root.right = new Node(3);        root.left.left = new Node(4);        root.right.left = new Node(5);        root.right.right = new Node(8);        root.right.left.left = new Node(6);        root.right.left.right = new Node(7);        root.right.right.left = new Node(9);        root.right.right.right = new Node(10);Â
        // Define the values of the nodes        int[] node_values            = { 2, 3, 4, 4, 7, 6, 2, 3, 9, 1 };Â
        // Call the function to get the sum of nodes at        // different levels        getSum(node_values, root);    }} |
Python3
# a binary tree nodeclass Node:    def __init__(self, data):        self.data = data        self.left = None        self.right = NoneÂ
def newNode(data):Â Â Â Â return Node(data)Â
def getSum(node_values, root):Â Â Â Â q = []Â Â Â Â q.append(root)Â Â Â Â level = 0Â Â Â Â while len(q) != 0:Â Â Â Â Â Â Â Â n = len(q)Â Â Â Â Â Â Â Â total = 0Â Â Â Â Â Â Â Â for i in range(n):Â Â Â Â Â Â Â Â Â Â Â Â front_node = q.pop(0)Â Â Â Â Â Â Â Â Â Â Â Â total += node_values[front_node.data - 1]Â Â Â Â Â Â Â Â Â Â Â Â if front_node.left:Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â q.append(front_node.left)Â Â Â Â Â Â Â Â Â Â Â Â if front_node.right:Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â q.append(front_node.right)Â Â Â Â Â Â Â Â print(f"Sum of level {level} : {total}")Â Â Â Â Â Â Â Â level += 1Â
# driver code to test above functionroot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.left = newNode(4)root.right.left = newNode(5)root.right.right = newNode(8)root.right.left.left = newNode(6)root.right.left.right = newNode(7)root.right.right.left = newNode(9)root.right.right.right = newNode(10)Â
node_values = [2, 3, 4, 4, 7, 6, 2, 3, 9, 1]Â
# function call to get the sum# of nodes of different levelgetSum(node_values, root) |
Javascript
// a binary tree nodeclass Node {Â Â constructor(data) {Â Â Â Â this.data = data;Â Â Â Â this.left = null;Â Â Â Â this.right = null;Â Â }}Â
function newNode(data) {Â Â return new Node(data);}Â
function getSum(node_values, root) {Â Â let q = [];Â Â q.push(root);Â Â let level = 0;Â Â while(q.length !== 0){Â Â Â Â let n = q.length;Â Â Â Â let sum = 0;Â Â Â Â for(let i = 0; i < n; i++){Â Â Â Â Â Â let front_node = q.shift();Â Â Â Â Â Â sum += node_values[front_node.data - 1];Â Â Â Â Â Â if(front_node.left) q.push(front_node.left);Â Â Â Â Â Â if(front_node.right) q.push(front_node.right);Â Â Â Â }Â Â Â Â console.log(`Sum of level ${level} : ${sum}`);Â Â Â Â level++;Â Â }}Â
// driver code to test above functionlet root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.right.left = newNode(5);root.right.right = newNode(8);root.right.left.left = newNode(6);root.right.left.right = newNode(7);root.right.right.left = newNode(9);root.right.right.right = newNode(10);Â
let node_values = [2, 3, 4, 4, 7, 6, 2, 3, 9, 1];Â
// function call to get the sum// of nodes of different levelgetSum(node_values, root); |
C#
using System;using System.Collections.Generic;Â
public class Node{Â Â Â Â public int data;Â Â Â Â public Node left, right;Â Â Â Â public Node(int data){Â Â Â Â Â Â Â Â this.data = data;Â Â Â Â Â Â Â Â this.left = this.right = null;Â Â Â Â }};Â
public class Gfg{Â Â Â Â public static Node newNode(int data){Â Â Â Â Â Â Â Â return new Node(data);Â Â Â Â }Â
    public static void getSum(int[] node_values, Node root){        Queue<Node> q = new Queue<Node>();        q.Enqueue(root);        int level = 0;        while(q.Count != 0){            int n = q.Count;            int sum = 0;            for(int i = 0; i<n; i++){                Node front_node = q.Peek();                q.Dequeue();                sum += node_values[front_node.data - 1];                if(front_node.left != null) q.Enqueue(front_node.left);                if(front_node.right != null) q.Enqueue(front_node.right);            }            Console.WriteLine("Sum of level "+level+" : "+sum);            level++;        }    }Â
    public static void Main(){        Node root = newNode(1);        root.left = newNode(2);        root.right = newNode(3);        root.left.left = newNode(4);        root.right.left = newNode(5);        root.right.right = newNode(8);        root.right.left.left = newNode(6);        root.right.left.right = newNode(7);        root.right.right.left = newNode(9);        root.right.right.right = newNode(10);             int[] node_values = new int[]{2,3,4,4,7,6,2,3,9,1};             // function call to get the sum        // of nodes of different level        getSum(node_values, root);    }} |
Sum of level 0 : 2 Sum of level 1 : 7 Sum of level 2 : 14 Sum of level 3 : 18
Time Complexity: O(N) where N is the number of nodes in given Binary Tree.
Auxiliary Space: O(N) due to queue data structure.
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/calculate-sum-of-all-nodes-present-in-a-level-for-each-level-of-a-tree/ […]
… [Trackback]
[…] Find More Information here to that Topic: geeksforgeeks.org/calculate-sum-of-all-nodes-present-in-a-level-for-each-level-of-a-tree/ […]