题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.size()==0){
return false;
}
return helper(sequence, 0, sequence.size() - 1);
}
private:
bool helper(vector<int> &sequence, int left, int right){
if(left==right){
return true;
}
int root = sequence[right];
int i = left;
for (; i <= right - 1; i++){
if (sequence[i]>root){
break;
}
}
int j = i;
for (; j <= right - 1; j++){
if (sequence[j]<root){
return false;
}
}
bool le =true;
if (i - 1>=left){
le = helper(sequence, left, i - 1);
}
bool ri =true;
if (i<=right - 1){
ri = helper(sequence, i, right - 1);
}
return le && ri;
}
};