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.
- 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
- Find sum of all right leaves in a given Binary Tree
- Find sum of all left leaves in a given Binary Tree
- Find first non matching leaves in two binary trees
- Find the maximum path sum between two leaves of a binary tree
- Find pairs in array whose sums already exist in array
- Find the Number of Maximum Product Quadruples
- Find pair with greatest product in array
- Check if all leaves are at same level
- Find maximum level product in Binary Tree
- Minimum sum path between two leaves of a binary tree
- Height of binary tree considering even level leaves only
- Print all nodes in a binary tree having K leaves
- Extract Leaves of a Binary Tree in a Doubly Linked List
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.