解题思路:
(1)最后一个肯定为根结点
(2)将其划分为左子树和右子树,分别递归判断
(3)注意左右子树的划分方法
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.size()==0) return false;
return Judge(sequence,0,sequence.size()-1);
}
bool Judge(vector<int> &v,int begin,int end) {
if(begin>=end) return true;
int left = left_right(v,begin,end);
if(left==-2) return false;
else return Judge(v,begin,left)&&Judge(v,left+1,end-1);
}
int left_right(vector<int> &v,int begin,int end){
int i=begin,left;
while(i<end && v[i]<v[end]) i++;
left = i;
while(i<end && v[i]>v[end]) i++;
if(i!=end) return -2;
else return left-1;
}
};