Given a Binary Tree. The task is to write a program to find the product of all of the nodes of the given binary tree.
👁 Image
In the above binary tree,
Product = 15*10*8*12*20*16*25 = 115200000
The idea is to recursively:
- Find the product of the left subtree.
- Find the product of the right subtree.
- Multiply the product of left and right subtrees with the current node's data and return.
Below is the implementation of the above approach:
OutputProduct of all the nodes is: 40320
Complexity Analysis
- Time complexity : O(n)
- As we are traversing the tree only once.
- Auxiliary Complexity: O(h)
- Here h is the height of the tree. The extra space is used in recursion call stack. In the worst case(when the tree is skewed) this can go upto O(n).