Given an N-ary tree, find sum of all elements in it.
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 :
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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Top three elements in binary tree
- XOR of elements in a given range with updates using Fenwick Tree
- Queries for elements greater than K in the given index range using Segment Tree
- Queries for elements having values within the range A to B in the given index range using Segment Tree
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Check if max sum level of Binary tree divides tree into two equal sum halves
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Convert a given Binary tree to a tree that holds Logical OR property
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Convert a given Binary tree to a tree that holds Logical AND property
- Sub-tree with minimum color difference in a 2-coloured tree
- Minimum difference between any two weighted nodes in Sum Tree of the given Tree
- Cartesian tree from inorder traversal | Segment Tree
- Difference between General tree and Binary tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.