题目描述:
Given an array arr of positive integers, consider all binary trees such that:
- Each node has either 0 or 2 children;
- The values of
arrcorrespond to the values of each leaf in an in-order traversal of the tree. (Recall that a node is a leaf if and only if it has 0 children.) - The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree respectively.
Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.
Example 1:
Input: arr = [6,2,4]
Output: 32
Explanation:
There are two possible trees. The first has non-leaf node sum 36, and the second has non-leaf node sum 32.
24 24
/ \ / \
12 4 6 8
/ \ / \
6 2 2 4
Constraints:
2 <= arr.length <= 401 <= arr[i] <= 15- It is guaranteed that the answer fits into a 32-bit signed integer (ie. it is less than
2^31).
构建树的过程就是两个相邻节点合并的过程,采用贪心的方法每次都找乘积最小的两个节点。
class Solution {
public:
int mctFromLeafValues(vector<int>& arr) {
int cost=0;
while(arr.size()>=2)
{
int min_index=0;
int min_product=INT_MAX;
for(int i=0;i<arr.size()-1;i++)
{
if(arr[i]*arr[i+1]<min_product)
{
min_index=i;
min_product=arr[i]*arr[i+1];
}
}
cost+=min_product;
arr[min_index]=max(arr[min_index],arr[min_index+1]);
arr.erase(arr.begin()+min_index+1);
}
return cost;
}
};
本文探讨了一种构建二叉树的方法,旨在寻找所有可能的二叉树中,非叶节点之和最小的那棵树。通过贪心算法,每次合并乘积最小的两个相邻节点,直至构建出满足条件的树。示例展示了输入数组[6,2,4]时,如何通过不同树结构得到最小非叶节点和32。
2995

被折叠的 条评论
为什么被折叠?



