Open In App

Sum of all elements of N-ary Tree

Last Updated : 21 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given an n-ary tree consisting of n nodes, the task is to find the sum of all the elements in the given n-ary tree.

Example:

Input:

second-largest-element-in-n-ary-tree-1

Output: 268
Explanation: The sum of all the nodes is 11 + 21 + 29 + 90 + 18 + 10 + 12 + 77 = 268

Input:

second-largest-element-in-n-ary-tree-2

Output: 360
Explanation: The sum of all the nodes is 81 + 26 + 23 + 49 + 95 + 86 = 360

Approach:

The idea is to use Level Order traversal in a binary tree. Start by pushing the root node in the queue. And for each node, while popping it from queue, add the value of this node in the sum variable and push the children of the popped element in the queue.

Below is the implementation of the above idea : 

C++
// C++ implementation to find the sum 
// of all nodes in the given N-ary tree
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    vector<Node*> children;

    Node(int val) {
        data = val;
    }
};

// Function to find the sum of all 
// nodes in the N-ary tree
int sumOfNodes(Node* root) {
    
    // Check if the tree is empty
    if (!root) return 0;  

    int sum = 0;
    queue<Node*> q;
    
    q.push(root);

    while (!q.empty()) {
        Node* curr = q.front();
        q.pop();

        // Add current node's value to the sum
        sum += curr->data;

        // Add all children of the current 
        // node to the queue
        for (auto child : curr->children) {
            q.push(child);
        }
    }

    return sum;
}

int main() {
    
     // Representation of given N-ary tree
    //         11
    //       /  |  \
    //     21   29  90
    //    /    /  \   \
    //   18   10  12  77
    Node* root = new Node(11);
    root->children.push_back(new Node(21));
    root->children.push_back(new Node(29));
    root->children.push_back(new Node(90));
    root->children[0]->children.push_back(new Node(18));
    root->children[1]->children.push_back(new Node(10));
    root->children[1]->children.push_back(new Node(12));
    root->children[2]->children.push_back(new Node(77));

    cout << sumOfNodes(root) << endl;

    return 0;
}
Java
// Java implementation to find the sum 
// of all nodes in the given N-ary tree
import java.util.*;

class Node {
    int data;
    List<Node> children;

    Node(int val) {
        data = val;
        children = new ArrayList<>();
    }
}

class GfG {
    
    // Function to find the sum of all 
    // nodes in the N-ary tree
    static int sumOfNodes(Node root) {

        // Check if the tree is empty
        if (root == null) return 0;

        int sum = 0;
        Queue<Node> q = new LinkedList<>();
        q.add(root);

        while (!q.isEmpty()) {
            Node curr = q.poll();

            // Add current node's value to the sum
            sum += curr.data;

            // Add all children of the current 
            // node to the queue
            for (Node child : curr.children) {
                q.add(child);
            }
        }

        return sum;
    }

    public static void main(String[] args) {
      
		// Representation of given N-ary tree
        //         11
        //       /  |  \
        //     21   29  90
        //    /    /  \   \
        //   18   10  12  77
        Node root = new Node(11);
        root.children.add(new Node(21));
        root.children.add(new Node(29));
        root.children.add(new Node(90));
        root.children.get(0).children.add(new Node(18));
        root.children.get(1).children.add(new Node(10));
        root.children.get(1).children.add(new Node(12));
        root.children.get(2).children.add(new Node(77));

        System.out.println(sumOfNodes(root));
    }
}
Python
# Python implementation to find the sum
# of all nodes in the given N-ary tree
from collections import deque

class Node:
    def __init__(self, val):
        self.data = val
        self.children = []

# Function to find the sum of all 
# nodes in the N-ary tree
def sum_of_nodes(root):
    
    # Check if the tree is empty
    if not root:
        return 0

    total_sum = 0
    q = deque([root])

    while q:
        curr = q.popleft()

        # Add current node's value to
        # the sum
        total_sum += curr.data

        # Add all children of the current
        # node to the queue
        for child in curr.children:
            q.append(child)

    return total_sum

if __name__ == '__main__':
  
   # Representation of given N-ary tree
  #         11
  #       /  |  \
  #     21   29  90
  #    /    /  \   \
  #   18   10  12  77
  root = Node(11)
  root.children.append(Node(21))
  root.children.append(Node(29))
  root.children.append(Node(90))
  root.children[0].children.append(Node(18))
  root.children[1].children.append(Node(10))
  root.children[1].children.append(Node(12))
  root.children[2].children.append(Node(77))

  print(sum_of_nodes(root))
C#
// C# implementation to find the sum 
// of all nodes in the given N-ary tree
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public List<Node> children;

    public Node(int val) {
        data = val;
        children = new List<Node>();
    }
}

class GfG {

    // Function to find the sum of all 
    // nodes in the N-ary tree
    static int SumOfNodes(Node root) {
        
        // Check if the tree is empty
        if (root == null)
            return 0;

        int sum = 0;
        Queue<Node> q = new Queue<Node>();
        
        q.Enqueue(root);

        while (q.Count > 0) {
            Node curr = q.Dequeue();

            // Add current node's value to the sum
            sum += curr.data;

            // Add all children of the current 
            // node to the queue
            foreach (Node child in curr.children) {
                q.Enqueue(child);
            }
        }

        return sum;
    }

    static void Main() {

        // Representation of given N-ary tree
        //         11
        //       /  |  \
        //     21   29  90
        //    /    /  \   \
        //   18   10  12  77
        Node root = new Node(11);
        root.children.Add(new Node(21));
        root.children.Add(new Node(29));
        root.children.Add(new Node(90));
        root.children[0].children.Add(new Node(18));
        root.children[1].children.Add(new Node(10));
        root.children[1].children.Add(new Node(12));
        root.children[2].children.Add(new Node(77)); 

        Console.WriteLine(SumOfNodes(root));
    }
}
JavaScript
// Javascript implementation to find the sum 
// of all nodes in the given N-ary tree
class Node {
    constructor(val) {
        this.data = val;
        this.children = [];
    }
}

// Function to find the sum of all 
// nodes in the N-ary tree
function sumOfNodes(root) {
    
    // Check if the tree is empty
    if (root === null) 
        return 0;

    let sum = 0;
    let q = [];

    q.push(root);

    while (q.length > 0) {
        let curr = q.shift();

        // Add current node's value to the sum
        sum += curr.data;

        // Add all children of the current 
        // node to the queue
        for (let child of curr.children) {
            q.push(child);
        }
    }

    return sum;
}

// Representation of given N-ary tree
//         11
//       /  |  \
//     21   29  90
//    /    /  \   \
//   18   10  12  77
const root = new Node(11);
root.children.push(new Node(21));
root.children.push(new Node(29));
root.children.push(new Node(90));
root.children[0].children.push(new Node(18));
root.children[1].children.push(new Node(10));
root.children[1].children.push(new Node(12));
root.children[2].children.push(new Node(77));

console.log(sumOfNodes(root)); 

Output
268

Time Complexity: O(n), where n is the number of nodes.
Auxiliary Space : O(n)


Next Article
Article Tags :
Practice Tags :

Similar Reads