VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-elements-n-ary-tree/

⇱ Sum of all elements of N-ary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of all elements of N-ary Tree

Last Updated : 11 Jul, 2025

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 : 


Output
268

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

Comment
Article Tags:
Article Tags: