Generate Complete Binary Tree in such a way that sum of non-leaf nodes is minimum
Given an array arr[] of size N, the task is to generate a Complete Binary Tree in such a way that sum of the non-leaf nodes is minimum, whereas values of the leaf node corresponds 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
Examples:
Input: arr[] = {1, 2, 3, 4}
Output: 20
Explanation:
Please refer below for explanation
Input: arr[] = {5, 2, 3}
Output: 21
Approach:
To remove a number arr[i], it needs a cost a * b, where b >= a and also an element of the array. To minimize the cost of removal, the idea is to minimize b. To compute the non-leaf node there are two candidates, that is the first largest number on the left and the first largest number on the right. The cost to remove arr[i] is a * min(left, right). It can be further decomposed as to find the next greater element in the array, on the left and one right.
Refer: Next greater element
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int MinCostTree( int arr[], int n)
{
int ans = 0;
vector< int > st = { INT_MAX };
for ( int i = 0; i < n; i++) {
while (st.back() <= arr[i]) {
int x = st.back();
st.pop_back();
ans += x * min(st.back(), arr[i]);
}
st.push_back(arr[i]);
}
for ( int i = 2; i < st.size(); i++)
ans += st[i] * st[i - 1];
return ans;
}
int main()
{
int arr[] = { 5, 2, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << MinCostTree(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int MinCostTree( int arr[], int n)
{
int ans = 0 ;
Vector<Integer> st = new Vector<Integer>();
st.add(Integer.MAX_VALUE);
for ( int i = 0 ; i < n; i++) {
while (st.get(st.size()- 1 ) <= arr[i]) {
int x = st.get(st.size()- 1 );
st.remove(st.size()- 1 );
ans += x * Math.min(st.get(st.size()- 1 ), arr[i]);
}
st.add(arr[i]);
}
for ( int i = 2 ; i < st.size(); i++)
ans += st.get(i) * st.get(i- 1 );
return ans;
}
public static void main(String[] args)
{
int arr[] = { 5 , 2 , 3 };
int n = arr.length;
System.out.print(MinCostTree(arr, n));
}
}
|
Python3
def MinCostTree(arr, n):
ans = 0
st = [ 2 * * 32 ]
for i in range (n):
while (st[ - 1 ] < = arr[i]):
x = st[ - 1 ]
st.pop()
ans + = x * min (st[ - 1 ], arr[i])
st.append(arr[i])
for i in range ( 2 , len (st)):
ans + = st[i] * st[i - 1 ]
return ans
arr = [ 5 , 2 , 3 ]
n = len (arr)
print (MinCostTree(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int MinCostTree( int []arr, int n)
{
int ans = 0;
List< int > st = new List< int >();
st.Add( int .MaxValue);
for ( int i = 0; i < n; i++) {
while (st[st.Count-1] <= arr[i]) {
int x = st[st.Count-1];
st.RemoveAt(st.Count-1);
ans += x * Math.Min(st[st.Count-1], arr[i]);
}
st.Add(arr[i]);
}
for ( int i = 2; i < st.Count; i++)
ans += st[i] * st[i-1];
return ans;
}
public static void Main(String[] args)
{
int []arr = { 5, 2, 3 };
int n = arr.Length;
Console.Write(MinCostTree(arr, n));
}
}
|
Javascript
<script>
function MinCostTree(arr, n)
{
let ans = 0;
let st = new Array()
st.push(Number.MAX_SAFE_INTEGER);
for (let i = 0; i < n; i++) {
while (st[st.length -1] <= arr[i]) {
let x = st[st.length-1];
st.pop();
ans += x * Math.min(st[st.length - 1], arr[i]);
}
st.push(arr[i]);
}
for (let i = 2; i < st.length; i++)
ans += st[i] * st[i - 1];
return ans;
}
let arr = [ 5, 2, 3 ];
let n = arr.length;
document.write(MinCostTree(arr, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n), where n is the length of the given array.
Last Updated :
06 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...