1130. Minimum Cost Tree From Leaf Values
- Minimum Cost Tree From Leaf Values python solution
题目描述
Given an array arr of positive integers, consider all binary trees such that:
Each node has either 0 or 2 children;
The values of arr correspond 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.
解析
使用贪心算法求解,先找到数组中最小的元素,作为叶子节点。再选取其相邻的最小元素,组成配对。便会产生一个新的非叶子节点,一旦产生非叶子节点,最小的元素便不起作用,因为每一个非叶子节点的值是他的左右子树中最大的叶子节点乘积。
所以为了使最终的求和最小,需要尽早的将最小元素组合起来,越到后面,最小元素便不起作用。
class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
res=0
while(len(arr)>1):
min_index=arr.index(min(arr))
if 0< min_index<len(arr)-1:
res+=min(arr[min_index+1],arr[min_index-1])*arr[min_index]
else:
if min_index==0:
res+=arr[min_index]*arr[1]
else:
res+=arr[min_index]*arr[-2]
arr.pop(min_index)
return res
Reference
https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/340014/Greedy-python-solution