题目描述:
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
思路:根据二叉搜索树的性质我们可知,根结点左子树的所有节点全都小于根结点,右子树的所有节点全都大于根结点。又又后序遍历我们可知,最后一个点是根结点,因此递归判断左(右)子树是否小于(大于)根结点的值即可。
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 10000 + 10;
int post[maxn];
bool check(int l, int r){
if(l >= r)
return true;
int i = l;
while(post[i] < post[r])
i++;
for(int j = i; j < r; j++)
if(post[j] < post[r])
return false;
if(i == r)
i--;
return check(l, i-1) && check(i, r-1);
}
int main()
{
int n;
while(scanf("%d", &n) != EOF){
for(int i = 0; i < n; i++)
scanf("%d", &post[i]);
if(check(0, n-1))
printf("Yes\n");
else
printf("No\n");
}
return 0;
}