LeetCode 1130. Minimum Cost Tree From Leaf Values解题报告(python)

1130. Minimum Cost Tree From Leaf Values

  1. 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值