判断整数序列是不是二元查找树的后序遍历结果
#include <iostream>
using namespace std;
bool verifySquenceOfBST(int squence[], int length)
{
if (squence==NULL||length<=0)
{
return false;
}
int root=squence[length-1];
int i=0;
for(; i<length-1; ++i)
{
if (squence[i]>root)
{
break;
}
}
int j=i;
for (; j<length-1; ++j)
{
if (squence[j]<root)
{
return false;
}
}
bool left=true;
if (i>0)
{
left=verifySquenceOfBST(squence, i);
}
bool right=true;
if (i<length-1)
{
right=verifySquenceOfBST(squence, length-i-1);
}
return left&&right;
}
int main()
{
int squence1[]={5, 7, 6, 9, 11, 10, 8};
int squence2[]={7, 4, 6, 5};
int length1=sizeof(squence1)/sizeof(int);
int length2=sizeof(squence2)/sizeof(int);
if (verifySquenceOfBST(squence1, length1))
{
cout<<"squence1 is BST"<<endl;
}
else
{
cout<<"squence1 is not BST"<<endl;
}
if (verifySquenceOfBST(squence2, length2))
{
cout<<"squence2 is BST"<<endl;
}
else
{
cout<<"squence2 is not BST"<<endl;
}
return 0;
}