class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.empty()) return false;
vector<int> inorder(sequence);
sort(inorder.begin(), inorder.end());
return IsPopOrder(inorder, sequence);
}
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
int n = pushV.size();
stack<int> stk; // 使用STL中的栈容器
int i = 0, j = 0;
while(i < n){
stk.push(pushV[i]); // 首先将pushV[i]入栈
while(!stk.empty() && stk.top() == popV[j]){ // 不断检查栈顶
++j;
stk.pop();
}
++i;
}
return j == n; // 判断能否成功对应
}
};
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.size() == 0)return false;
return check(sequence, 0, sequence.size()-1);
}
bool check(vector<int>sequnce,int l,int r){
if(l >= r){
return true;//只有一个节点,返回true
}
int root = sequnce[r];//根节点
int j = r-1;
while(j >= 0 && sequnce[j] > root){
j--;//查找左右子树的分界点
}
for(int i = 0; i < j; i++){
if(sequnce[i] > root){
return false;//如果左子树有大于根节点的数,则不是二叉搜索树
}
}
return check(sequnce, l, j) && check(sequnce, j + 1, r -1);
}
};