解题思路
- 单调栈
- 后序遍历
代码
// 自后向前,维护一个单调递减的栈,成功返回true
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
stack<int>s;
int top=INT_MAX;
for(auto p=rbegin(postorder);p!=rend(postorder);p++){
int val=*p;
if(val>top)return false;
while(!s.empty() && val<s.top()){
top=s.top();
s.pop();
}
s.push(val);
}
return true;
}
};