Min-Max Product Tree of a given Binary Tree
Given a Binary Tree, the task is to convert the given Binary tree into Min-Max Product Tree and print the level-order sequence of the modified tree.
Min-Max Product Tree: A Min-Max Product Tree contains the product of the minimum and maximum values of its left and right subtrees at each node.
Note: For any node having only a single child, the value of that child node will be considered as both the minimum and the maximum.
Input: 1 / \ 12 11 / / \ 3 4 13 \ / 15 5 Output: 45 9 60 3 225 25 15 5 Explanation: Min-Max Product Tree: 45 (3 * 15) / \ ( 3 * 3)9 60 (4 * 15) / / \ 3 225 25 (5* 5) \ / 15 5 Input: 5 / \ 21 77 / \ \ 61 16 16 \ / 10 3 / 23 Output: 231 610 48 61 230 9 529 3 23
The idea is to use the post order traversal to traverse the left and right subtree recursively and extract the minimum and maximum. Store the product of minimum and maximum for every node in the Min-Max Product tree. Once, computed, compare the current node value with the current minimum and maximum and modify accordingly. Return the new minimum and maximum for the node at a higher level. Repeat this process for all nodes and finally, print the level order traversal of the Min-Max Product tree.
Below is the implementation of the above approach:
144 48 294 203 294 7 29 42 49 7
Time Complexity: O(N), where N denotes the number of nodes in the binary tree
Auxiliary Space: O(1)
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.