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.