Given an array/list ‘ARR' of size ‘N’, the task is to generate a Complete Binary Tree in such a way that the sum of the non-leaf nodes is minimum, whereas values of the leaf node correspond to the array elements in an In-order Traversal of the tree and value of each non-leaf node corresponds to the product of the largest leaf value in the left sub-tree and right sub-tree.
Example:
Let's say we have an 'ARR' = {1, 2, 3, 4}, so the possible complete
binary trees will be:
4 12
/ \ / \
1 8 6 4
/ \ / \
2 12 2 3
/ \ / \
3 4 1 2
Sum of non-leaf nodes = 24 Sum of non-leaf nodes = 20
So the required answer you have to return is 20.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of every test case contains an integer ‘N’ denoting the number of array elements.
The second line of every test case contains 'N' space-separated integers denoting the inorder traversal of leaf nodes of a complete binary tree.
Output format:
For each test case, return the minimum possible sum of non-leaf nodes of a binary tree.
Output for each test case is printed on a separate line.
Note:
1.You do not need to print anything, it has already been taken care of. Just return the minimum possible sum of all non-leaf nodes.
2. It is guaranteed that the answer fits into a 32-bit signed integer (ie. it is less than 2^31).
1 <= T <= 10
2 <= N <= 40
1 <= ARR[i] <= 15
Where ‘ARR[i]’ represents the array elements.
Time limit: 1 sec
2
4
1 2 3 4
3
6 2 4
20
32
In test case 1, It is already explained above in the example.
In test case 2, There are two possible trees. The first has a non-leaf node sum of 36, and the second has a non-leaf node sum of 32. So the required answer is 32
24 24
/ \ / \
12 4 6 8
/\ / \
6 2 2 4
2
3
5 2 3
4
5 3 2 1
21
23
Try to solve the problem by breaking it into subproblems(recursive approach)
Approach:
Algorithm:
O(2^N), Where ‘N’ is the number of leaf nodes.
Since we are using a recursive function to find the minimum sum where we are comparing each subarray maximum value and from it calculating the minimum sum. So the overall time complexity will be O(2^N).
O(N), Where ‘N’ is the number of leaf nodes.
Since we are using a recursive function and in the worst case, there can be O(N) states in the call stack, the overall space complexity will be O(N).