题目:http://ac.jobdu.com/problem.php?cid=1039&pid=9
-
题目描述:
-
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
-
输入:
-
每个测试案例包括2行:
第一行为1个整数n(1<=n<=10000),表示数组的长度。
第二行包含n个整数,表示这个数组,数组中的数的范围是[0,100000000]。
-
输出:
-
对应每个测试案例,如果输入数组是某二叉搜索树的后序遍历的结果输出Yes,否则输出No。
-
样例输入:
-
7
5 7 6 9 11 10 8
4
7 4 6 5
-
样例输出:
-
Yes
No
本题意思就是判断输入的二叉树的后序遍历,判断这棵树是否是二叉搜索树。而且根据二叉搜索树的性质:根结点值大于左子树,小于右子树。
因此,从根结点出发,向前找到所有连续的大于根结点的值作为右子树,再往前的所有连续小于根结点的作为左子树,如果往前还有大于根结点的,则不是二叉搜索树的后序遍历结果。
以下是AC代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <string.h>
#include <algorithm>
#include <cmath>
using namespace std;
#define N 10100
int judge(int n,int p[])
{
if(n <= 2)
return 1;
int i , pos;
pos = p[n - 1];//根结点
for(i = 0;i <n - 1;i++)//左子树
if(p[i] > pos)
break;
for(;i < n - 1;i++)//右子树
if(p[i] < pos)
return 0;
return 1;
}
int main()
{
int n , i;
int p[N];
while(scanf("%d",&n) == 1)
{
for(i = 0;i < n;i++)
scanf("%d",&p[i]);
if(judge(n,p))
printf("Yes\n");
else
printf("No\n");
}
return 0;
}