LeetCode #1130. Minimum Cost Tree From Leaf Values

本文探讨了一种构建二叉树的方法,旨在寻找所有可能的二叉树中,非叶节点之和最小的那棵树。通过贪心算法,每次合并乘积最小的两个相邻节点,直至构建出满足条件的树。示例展示了输入数组[6,2,4]时,如何通过不同树结构得到最小非叶节点和32。

题目描述:

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.

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 <= 40
  • 1 <= 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.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值