text: Product of nodes at k | C ++ implementation to find product of elements at k - th level ; Recursive Function to find product of elements at k - th level ; if subtree is null , just like if root == NULL ; Consider only level k node to be part of the product ; Recur for Left Subtree ; Recur for Right Subtree ; Taking care of ' ) ' after left and right subtree ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int productAtKthLevel ( string tree , int k , int & i , int level ) { if ( tree [ i ++ ] == ' ( ' ) { if ( tree [ i ] == ' ) ' ) return 1 ; int product = 1 ; if ( level == k ) product = tree [ i ] - '0' ; int leftproduct = productAtKthLevel ( tree , k , ++ i , level + 1 ) ; int rightproduct = productAtKthLevel ( tree , k , ++ i , level + 1 ) ; ++ i ; return product * leftproduct * rightproduct ; } } int main ( ) { string tree = " ( 0(5(6 ( ) ( ) ) ( 4 ( ) " " ( 9 ( ) ( ) ) ) ) ( 7(1 ( ) ( ) ) ( 3 ( ) ( ) ) ) ) " ; int k = 2 ; int i = 0 ; cout << productAtKthLevel ( tree , k , i , 0 ) ; return 0 ; }