- 时间限制:1秒空间限制:32768K
- 通过比例:22.66%
- 最佳记录:0ms|8552K(来自 牛客688826号)
题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.empty()) return false;
vector<int> left,right;
int root=sequence[sequence.size()-1];
int i=0;
for(;i<sequence.size()-1;++i){
if(sequence[i]<root) left.push_back(sequence[i]);
else break;
}
for(;i<sequence.size()-1;++i){
if(sequence[i]>root) right.push_back(sequence[i]);
else break;
}
if(left.size()+right.size()!=sequence.size()-1) return false;
if(left.empty()||right.empty()) return true;
return VerifySquenceOfBST(left)&&VerifySquenceOfBST(right);
}
};