參考連接:spa
https://blog.csdn.net/qq_17550379/article/details/97020009.net
https://blog.csdn.net/qq_17550379/article/details/86519771code
題意:一顆二叉樹每一個結點只能有0個或2個孩子,arr裏面是這顆樹的中序遍歷中的全部的葉子結點,每一個非葉結點的值等於其左子樹和右子樹中葉結點的最大值的乘積,返回最小的非葉結點的值的可能總和。blog
如:上面的例子中,(左)6*2 + 6*4 = 12 + 24 = 36 , (右)6*4 + 2*4 = 24 + 8 = 32排序
故,最後答案是32get
再舉一個例子:arr = [6, 2, 4, 5, 7, 8]it
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; } };