Given a Binary Tree, return following value for it.
- For every level, compute sum of all leaves if there are leaves at this level. Otherwise ignore it.
- Return multiplication of all sums.
Input: Root of below tree 2 / \ 7 5 \ 9 Output: 63 First levels doesn't have leaves. Second level has one leaf 7 and third level also has one leaf 9. Therefore result is 7*9 = 63 Input: Root of below tree 2 / \ 7 5 / \ \ 8 6 9 / \ / \ 1 11 4 10 Output: 208 First two levels don't have leaves. Third level has single leaf 8. Last level has four leaves 1, 11, 4 and 10. Therefore result is 8 * (1 + 11 + 4 + 10)
Here, we are simply doing preorder traversal of the binary tree, and we have used unordered_map in C++ STL to store sum of leaf nodes at same level. Then in a single traversal of the map, we’ve calculated the final product of level sums.
Below is the implementation of above approach:
Final product is = 208
Time Complexity: O(N)
Auxiliary Space: O(N)
Where N is the number of nodes in the Binary Tree.
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.
- Find multiplication of sums of data of leaves at same levels
- Tree with N nodes and K leaves such that distance between farthest leaves is minimized
- Check if all leaves are at same level
- Find the maximum path sum between two leaves of a binary tree
- Find sum of all left leaves in a given Binary Tree
- Find first non matching leaves in two binary trees
- Find sum of all right leaves in a given Binary Tree
- Print Binary Tree levels in sorted order | Set 2 (Using set)
- Print all the levels with odd and even number of nodes in it | Set-2
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Extract Leaves of a Binary Tree in a Doubly Linked List
- Print all nodes in a binary tree having K leaves
- Height of binary tree considering even level leaves only
- Minimum sum path between two leaves of a binary tree
- Count of nodes which are at a distance X from root and leaves
- Minimum count of Full Binary Trees such that the count of leaves is N
- Check if N leaves only distinct remainders on division by all values up to K
- Mimimum number of leaves required to be removed from a Tree to satisfy the given condition
- Find pairs in array whose sums already exist in array
- Reverse alternate levels of a perfect 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.