![]() |
VOOZH | about |
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-1Output: 268
Explanation: The sum of all the nodes is 11 + 21 + 29 + 90 + 18 + 10 + 12 + 77 = 268Input:
👁 second-largest-element-in-n-ary-tree-2Output: 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 :
268
Time Complexity: O(n), where n is the number of nodes.
Auxiliary Space : O(n)