这里假设数列中没有重复元素。根据二叉搜索树的特点,左子树所有节点值小于根节点,右子树所有节点值大于根节点。在后序遍历序列中,最后一个元素对应二叉搜索树根节点,我们从数组左边找到第一个比根节点大的元素,看这个元素右边(除过最后一个元素)值是否都比根节点值大,若不是,则表明这个不是一个有效的后序序列,返回false。程序可以用递归实现如下:(测试样例结果分别为true, false)
#include <iostream>
#include <queue>
using namespace std;
struct BiTreeNode{
int val;
BiTreeNode* leftChild;
BiTreeNode* rightChild;
};
bool VerifySequence(int *arr, int length){
if (arr == NULL || length <= 0)
return false;
int rootVal = arr[length - 1];
int pos = 0;
for (; pos < length - 1; ++pos){
if (arr[pos] > rootVal)
break;
}
for (int i = pos; i < length - 1; ++i){
if (arr[i] < rootVal)
return false;
}
bool left = true, right = true;
if (pos > 0){
left = VerifySequence(arr, pos);
}
if (pos < length - 1){
right = VerifySequence(arr + pos, length - 1 - pos);
}
return left && right;
}
void main(int argc, char* argv[])
{
int arr1[] {5, 7, 6, 9, 11, 10, 8};
int arr2[] {7, 4, 6, 5};
cout << VerifySequence(arr1, 7);
cout << VerifySequence(arr2, 4);
system("pause");
}