题解 | 二叉搜索树的后序遍历序列
二叉搜索树的后序遍历序列
https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd
class Solution {
public:
//对需要检验的后序遍历序列进行排序,检验它是否可以是排序后的序列(中序)的出栈顺序;是则true
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.size() == 0)return false;
stack<int> stk;
vector<int> vinorder(sequence);
sort(vinorder.begin(), vinorder.end());
int j=0;
for(int i=0; i<vinorder.size(); ++i){
stk.push(vinorder[i]);
while(!stk.empty() && stk.top() == sequence[j]){
stk.pop();
++j;
}
}
return j == sequence.size()? true: false;
}
};
查看9道真题和解析