题目:
输入一个非空整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
//判断是否是搜索二叉树的遍历
//搜索二叉树:左子树小于根节点,右边子树大于根节点
//从数组后面开始遍历,找到右子树的边界,然后递归右子树
//判断左子树序列中是否存在比根节点大的数,如果没有递归左子树,如果有返回false
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
int size = sequence.size();
if(size <= 0) return false;
int root = sequence[size -1];
int idx = size - 2;
vector<int>right;
while(idx >= 0 && sequence[idx] > root){
right.push_back(sequence[idx--]);
}
vector<int>left;
while(idx >= 0 && sequence[idx] < root){
left.push_back(sequence[idx--]);
}
if(idx!=-1) return false;
bool left_bool = true;
if(left.size() > 0)
left_bool = VerifySquenceOfBST(left);
bool right_bool = true;
if(right.size() > 0)
right_bool = VerifySquenceOfBST(right);
return left_bool&&right_bool;
}
};