思路:
比如给定序列 4 8 6 12 16 14 10
10是根节点,判断10左子树(4 8 6 )和右子树(12 16 14 )是否满足比10小,比10大,如果满足
继续判断(4 8 6 )和 (12 16 14 )各自是否满足,可以看出明显就是递归
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence)
{
int length = sequence.size();
if(length == 0)
return false;
if( check(sequence , 0, length - 1) )
return true;
else
return false;
}
//检查序列a到b有没有满足二叉搜索树
bool check(vector<int> sequence, int a, int b)
{
if(a >= 0 && a < b)//不止一个元素的时候
{
int root = sequence[b];
int start = -1;
for(int i = a; i < b; i++)
{
if(sequence[i] < root)
start = i;
else
break;
}
if(start == -1)//二叉搜索树根节点没有左子树
{
for(int i = a;i < b; i++)
{
if(sequence[i] < root)//右子树比根节点小
return false;
}
return check(sequence, a, b-1);//递归检查右子树是否满足二叉搜索树
}
else//二叉搜索树有左子树
{
for(int i = start + 1; i < b; i++)//检查右子树是否满足
{
if(sequence[i] < root)
return false;//不满足
}
//检查根节点的左子树和右子树
return check(sequence, a, start) &&
check(sequence, start + 1, b-1);
}
}
return true;//序列只有一个元素的时候当做二叉搜索树了
}
};