题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
解题思路:根据后序遍历将数组分为左子树和右子树,若存在,分别判断左子树、右子树是否为后序遍历,当两者同为true时返回true,否则返回false。
代码如下:
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
vector<int>sLeft;
vector<int>sRight;
int n=sequence.size();
if(n==0)
return false;
if(n==1)
return true;
int root=sequence[n-1];
int index=0;
while(index<=n-1&&sequence[index]<root)
sLeft.push_back(sequence[index++]);
while(index<=n-1&&sequence[index]>root)
sRight.push_back(sequence[index++]);
int sum1=sLeft.size();
int sum2=sRight.size();
bool mark1=true,mark2=true;
if(sum1+sum2==n-1)
{
if(sum1)
mark1=VerifySquenceOfBST(sLeft);
if(sum2)
mark2=VerifySquenceOfBST(sRight);
if(mark1&&mark2)
return true;
else
return false;
}
return false;
}
};