Sum of all elements of N-ary Tree - GeeksforGeeks

08 Nov, 2021
Given an N-ary tree, find sum of all elements in it. 
Example :  
Input : Above tree
Output : Sum is 536
 
Approach : The approach used is similar to 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. In case of a generic tree store child nodes in a vector. Thus, put all elements of the vector in the queue.Below is the implementation of the above idea :  
C++
Java
Python3
C#
Javascript
// C++ program to find sum of all// elements in generic tree#include <bits/stdc++.h>using namespace std; // Represents a node of an n-ary treestruct Node {    int key;    vector<Node*> child;}; // Utility function to create a new tree nodeNode* newNode(int key){    Node* temp = new Node;    temp->key = key;    return temp;} // Function to compute the sum// of all elements in generic treeint sumNodes(Node* root){    // initialize the sum variable    int sum = 0;     if (root == NULL)        return 0;     // Creating a queue and pushing the root    queue<Node*> q;    q.push(root);     while (!q.empty()) {        int n = q.size();         // If this node has children        while (n > 0) {             // Dequeue an item from queue and            // add it to variable "sum"            Node* p = q.front();            q.pop();            sum += p->key;             // Enqueue all children of the dequeued item            for (int i = 0; i < p->child.size(); i++)                q.push(p->child[i]);            n--;        }    }    return sum;} // Driver programint main(){    // Creating a generic tree    Node* root = newNode(20);    (root->child).push_back(newNode(2));    (root->child).push_back(newNode(34));    (root->child).push_back(newNode(50));    (root->child).push_back(newNode(60));    (root->child).push_back(newNode(70));    (root->child[0]->child).push_back(newNode(15));    (root->child[0]->child).push_back(newNode(20));    (root->child[1]->child).push_back(newNode(30));    (root->child[2]->child).push_back(newNode(40));    (root->child[2]->child).push_back(newNode(100));    (root->child[2]->child).push_back(newNode(20));    (root->child[0]->child[1]->child).push_back(newNode(25));    (root->child[0]->child[1]->child).push_back(newNode(50));     cout << sumNodes(root) << endl;     return 0;}
// Java program to find sum of all// elements in generic treeimport java.util.*; class GFG{ // Represents a node of an n-ary treestatic class Node{    int key;    Vector<Node> child;}; // Utility function to create a new tree nodestatic Node newNode(int key){    Node temp = new Node();    temp.key = key;    temp.child = new Vector<>();    return temp;} // Function to compute the sum// of all elements in generic treestatic int sumNodes(Node root){    // initialize the sum variable    int sum = 0;     if (root == null)        return 0;     // Creating a queue and pushing the root    Queue<Node> q = new LinkedList<>();    q.add(root);     while (!q.isEmpty())    {        int n = q.size();         // If this node has children        while (n > 0)        {             // Dequeue an item from queue and            // add it to variable "sum"            Node p = q.peek();            q.remove();            sum += p.key;             // Enqueue all children of the dequeued item            for (int i = 0; i < p.child.size(); i++)                q.add(p.child.get(i));            n--;        }    }    return sum;} // Driver programpublic static void main(String[] args){    // Creating a generic tree    Node root = newNode(20);    (root.child).add(newNode(2));    (root.child).add(newNode(34));    (root.child).add(newNode(50));    (root.child).add(newNode(60));    (root.child).add(newNode(70));    (root.child.get(0).child).add(newNode(15));    (root.child.get(0).child).add(newNode(20));    (root.child.get(1).child).add(newNode(30));    (root.child.get(2).child).add(newNode(40));    (root.child.get(2).child).add(newNode(100));    (root.child.get(2).child).add(newNode(20));    (root.child.get(0).child.get(1).child).add(newNode(25));    (root.child.get(0).child.get(1).child).add(newNode(50));     System.out.print(sumNodes(root) +"\n");}} // This code is contributed by 29AjayKumar
# Python3 program to find sum of all# elements in generic tree # Represents a node of an n-ary treeclass Node:    def __init__(self):        self.key = 0        self.child = [] # Utility function to create a new tree nodedef newNode(key):    temp = Node()    temp.key = key    temp.child = []    return temp  # Function to compute the sum# of all elements in generic treedef sumNodes(root):    # initialize the sum variable    Sum = 0      if root == None:        return 0      # Creating a queue and pushing the root    q = []    q.append(root)      while len(q) != 0:        n = len(q)          # If this node has children        while n > 0:            # Dequeue an item from queue and            # add it to variable "sum"            p = q[0]            q.pop(0)            Sum += p.key              # push all children of the dequeued item            for i in range(len(p.child)):                q.append(p.child[i])            n-=1    return Sum # Creating a generic treeroot = newNode(20)(root.child).append(newNode(2))(root.child).append(newNode(34))(root.child).append(newNode(50))(root.child).append(newNode(60))(root.child).append(newNode(70))(root.child[0].child).append(newNode(15))(root.child[0].child).append(newNode(20))(root.child[1].child).append(newNode(30))(root.child[2].child).append(newNode(40))(root.child[2].child).append(newNode(100))(root.child[2].child).append(newNode(20))(root.child[0].child[1].child).append(newNode(25))(root.child[0].child[1].child).append(newNode(50))print(sumNodes(root)) # This code is contributed by divyeshrabadiya07.
     // C# program to find sum of all// elements in generic treeusing System;using System.Collections.Generic; class GFG{ // Represents a node of an n-ary treeclass Node{    public int key;    public List<Node> child;}; // Utility function to create a new tree nodestatic Node newNode(int key){    Node temp = new Node();    temp.key = key;    temp.child = new List<Node>();    return temp;} // Function to compute the sum// of all elements in generic treestatic int sumNodes(Node root){    // initialize the sum variable    int sum = 0;     if (root == null)        return 0;     // Creating a queue and pushing the root    Queue<Node> q = new Queue<Node>();    q.Enqueue(root);     while (q.Count != 0)    {        int n = q.Count;         // If this node has children        while (n > 0)        {             // Dequeue an item from queue and            // add it to variable "sum"            Node p = q.Peek();            q.Dequeue();            sum += p.key;             // Enqueue all children of the dequeued item            for (int i = 0; i < p.child.Count; i++)                q.Enqueue(p.child[i]);            n--;        }    }    return sum;} // Driver programpublic static void Main(String[] args){    // Creating a generic tree    Node root = newNode(20);    (root.child).Add(newNode(2));    (root.child).Add(newNode(34));    (root.child).Add(newNode(50));    (root.child).Add(newNode(60));    (root.child).Add(newNode(70));    (root.child[0].child).Add(newNode(15));    (root.child[0].child).Add(newNode(20));    (root.child[1].child).Add(newNode(30));    (root.child[2].child).Add(newNode(40));    (root.child[2].child).Add(newNode(100));    (root.child[2].child).Add(newNode(20));    (root.child[0].child[1].child).Add(newNode(25));    (root.child[0].child[1].child).Add(newNode(50));     Console.Write(sumNodes(root) +"\n");}} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to find sum of all// elements in generic tree // Represents a node of an n-ary treeclass Node{  constructor()  {    this.key = 0;    this.child = [];  }}; // Utility function to create a new tree nodefunction newNode(key){    var temp = new Node();    temp.key = key;    temp.child = [];    return temp;} // Function to compute the sum// of all elements in generic treefunction sumNodes(root){    // initialize the sum variable    var sum = 0;     if (root == null)        return 0;     // Creating a queue and pushing the root    var q = [];    q.push(root);     while (q.length != 0)    {        var n = q.length;         // If this node has children        while (n > 0)        {             // Dequeue an item from queue and            // add it to variable "sum"            var p = q[0];            q.shift();            sum += p.key;             // push all children of the dequeued item            for (var i = 0; i < p.child.length; i++)                q.push(p.child[i]);            n--;        }    }    return sum;} // Driver program// Creating a generic treevar root = newNode(20);(root.child).push(newNode(2));(root.child).push(newNode(34));(root.child).push(newNode(50));(root.child).push(newNode(60));(root.child).push(newNode(70));(root.child[0].child).push(newNode(15));(root.child[0].child).push(newNode(20));(root.child[1].child).push(newNode(30));(root.child[2].child).push(newNode(40));(root.child[2].child).push(newNode(100));(root.child[2].child).push(newNode(20));(root.child[0].child[1].child).push(newNode(25));(root.child[0].child[1].child).push(newNode(50));document.write(sumNodes(root) +"<br>");  </script>
Output:  
536
Time Complexity: O(N), where N is the number of nodes in tree. Auxiliary Space: O(N), where N is the number of nodes in tree. 
YouTubeGeeksforGeeks506K subscribersSum of all elements of N-ary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:42•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=j3xeTJzobEw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
29AjayKumar
princiraj1992
rrrtnx
divyeshrabadiya07
cpp-vector
n-ary-tree
Recursion
Technical Scripter
Tree
Recursion
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Practice Questions for Recursion | Set 1
Recursively Reversing a linked list (A simple implementation)
Sum of natural numbers using recursion
Count N-length strings consisting only of vowels sorted lexicographically
Count number of nodes in a complete Binary Tree
Tree Traversals (Inorder, Preorder and Postorder)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)