单调栈 leetcode 1130.
Posted bella2017
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单调栈 leetcode 1130.相关的知识,希望对你有一定的参考价值。
参考链接:
https://blog.csdn.net/qq_17550379/article/details/97020009
https://blog.csdn.net/qq_17550379/article/details/86519771
题意:一颗二叉树每个结点只能有0个或2个孩子,arr里面是这颗树的中序遍历中的所有的叶子结点,每个非叶结点的值等于其左子树和右子树中叶结点的最大值的乘积,返回最小的非叶结点的值的可能总和。
如:上面的例子中,(左)6*2 + 6*4 = 12 + 24 = 36 , (右)6*4 + 2*4 = 24 + 8 = 32
故,最后答案是32
再举一个例子:arr = [6, 2, 4, 5, 7, 8]
class Solution public: int mctFromLeafValues(vector<int>& arr) stack<int> st; st.push(INT_MAX); int res = 0; for(int a : arr) while(st.top() <= a) int little = st.top(); st.pop(); res += little * min(st.top(), a); st.push(a); while(st.size()>2) //栈底到栈顶为从大到小排序,将它们从栈顶开始,两两相乘 int r = st.top(); st.pop(); res += r * st.top(); return res; ;
以上是关于单调栈 leetcode 1130.的主要内容,如果未能解决你的问题,请参考以下文章
[每日一题2020.06.19]leetcode #84 #121 单调栈