输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
if(sequence.empty())
{
return false;
}
return isSeqBST(sequence,0,sequence.size());
}
bool isSeqBST(vector<int> sequence, int start, int end)
{
int i = 0 , j = 0;
bool left = true, right = true;
int root = 0;
if((end-start) <= 0)
{
return false;
}
i = start;
root = sequence[end-1];
/* 找出左子树的节点 */
for(; i < end-1; i++)
{
if(sequence[i] > root)
{
break;
}
}
/* 判断右子树是否符合要求 */
for(j = i; j < end-1;j++)
{
if(sequence[j] < root)
{
return false;
}
}
/* 判断左子树是否符合二叉排序树 */
left = true;
if(i > start)
{
left = isSeqBST(sequence,start,i);
}
/* 判断右子树是否符合二叉排序树 */
right = true;
if(i < end-1)
{
right = isSeqBST(sequence,i,end-1);
}
return (left&&right);//还有左右均符合条件才可以
}
};