题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
分析:后序遍历,最后一个元素为根元素,从倒数第二个元素向前搜索,找到第一个比根小的元素,这里就是分开左右子树的地方,这时候如果再向前搜索,能发现比根还要大的元素,说明就不是BST。递归判断两棵子树。注意判断返回true的条件是low>=high,第一次写的low==high,出错了,因为举个例子看一下有可能会大于的。
代码:
class Solution {
public:
bool helper(vector<int> nums,int low,int high){
if(low>=high){
return true;
}
int root=nums[high];
int i=high-1;
while(nums[i]>nums[high]){
i--;
}
int p=i;
while(i>=low){
if(nums[i]>nums[high]) return false;
i--;
}
return helper(nums,low,p)&&helper(nums,p+1,high-1);
}
bool VerifySquenceOfBST(vector<int> sequence) {
int n=sequence.size();
if(n==0) return false;
return helper(sequence,0,n-1);
}
};