Give an algorithm for finding the sum of all elements in a binary tree.
In the above binary tree sum = 106.
The idea is to recursively, call left subtree sum, right subtree sum and add their values to current node’s data.
Sum of all the elements is: 36
This article is contributed by Prakriti Gupta. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Sum of all leaf nodes of binary tree
- Sum of heights of all individual nodes in a binary tree
- Find sum of all nodes of the given perfect binary tree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Sum of all the Boundary Nodes of a Binary Tree
- Maximum sum of leaf nodes among all levels of the given binary tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Sum of all the child nodes with even parent values in a Binary Tree
- Sum of all nodes at Kth level in a Binary Tree
- Sum of all the child nodes with even grandparents in a Binary Tree
- Check if all nodes of the Binary Tree can be represented as sum of two primes
- Count of all prime weight nodes between given nodes in the given Tree
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Sum of all odd nodes in the path connecting two given nodes
- Remove all leaf nodes from a Generic Tree or N-ary Tree