Product of nodes at k | Java 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
class GFG { static int i ; static int productAtKthLevel ( String tree , int k , int level ) { if ( tree . charAt ( i ++ ) == ' ( ' ) { if ( tree . charAt ( i ) == ' ) ' ) return 1 ; int product = 1 ; if ( level == k ) product = tree . charAt ( i ) - '0' ; ++ i ; int leftproduct = productAtKthLevel ( tree , k , level + 1 ) ; ++ i ; int rightproduct = productAtKthLevel ( tree , k , level + 1 ) ; ++ i ; return product * leftproduct * rightproduct ; } return Integer . MIN_VALUE ; } public static void main ( String [ ] args ) { String tree = " ( 0(5(6 ( ) ( ) ) ( 4 ( ) " + " ( 9 ( ) ( ) ) ) ) ( 7(1 ( ) ( ) ) ( 3 ( ) ( ) ) ) ) " ; int k = 2 ; i = 0 ; System . out . print ( productAtKthLevel ( tree , k , 0 ) ) ; } }