# （剑指Offer）面试题24：二叉搜索树的后序遍历序列

## 代码：

```#include <iostream>

using namespace std;

bool VerifySequenceOfBST(int sequence[],int length){
if(sequence==NULL || length<=0)
return false;
int root=sequence[length-1];

int leftIndex=0;
while(sequence[leftIndex]<root)
leftIndex++;

int rightIndex=leftIndex;
while(rightIndex<length-1){
if(sequence[rightIndex]<root)
return false;
rightIndex++;
}

bool left=true;
if(leftIndex>0)
left=VerifySequenceOfBST(sequence,leftIndex);

bool right=true;
if(leftIndex<length-1)
right=VerifySequenceOfBST(sequence+leftIndex,length-leftIndex-1);

return (left&&right);
}

int main()
{
int A[]={5,7,6,9,10,8};
int B[]={7,4,6,5};
int lengthA=sizeof(A)/sizeof(A[0]);
int lengthB=sizeof(B)/sizeof(B[0]);
cout << VerifySequenceOfBST(A,lengthA) << endl;
cout << VerifySequenceOfBST(B,lengthB) << endl;
return 0;
}```

## 在线测试OJ：

http://www.nowcoder.com/books/coding-interviews/a861533d45854474ac791d90e447bafd?rp=1

AC代码：

```class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
int length=sequence.size();
if(length<=0) return false;
return VerifySquence(sequence,0,length-1);
}

bool VerifySquence(vector<int> sequence,int begin,int end) {
if(begin>=end)
return true;

int root=sequence[end];
int leftIndex=begin;
while(sequence[leftIndex]<root)
++leftIndex;

int rightIndex=leftIndex;
while(rightIndex<end){
if(sequence[rightIndex]<root)
return false;
++rightIndex;
}

return VerifySquence(sequence,begin,leftIndex-1)&&VerifySquence(sequence,leftIndex,end-1);

}
};```
原文作者：AndyJee
原文地址: https://www.cnblogs.com/AndyJee/p/4651655.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。