[LeetCode] Minimum Cost Tree From Leaf Values

1130. Minimum Cost Tree From Leaf Values

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

A node is a leaf if and only if it has zero children.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int mctFromLeafValues(vector<int>& arr) {
vector<int> st;
int sum = 0;
for(int n : arr) {
while(!st.empty() and st.back() <= n) {
int mi = st.back();
st.pop_back();
sum += min(n, st.empty() ? INT_MAX : st.back()) * mi;
}
st.push_back(n);
}
for(int i = 0; i < st.size() - 1; i++) {
sum += st[i] * st[i+1];
}
return sum;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/15/PS/LeetCode/minimum-cost-tree-from-leaf-values/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.