L2-004 这是二叉搜索树吗? (25分)
一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,
其左子树中所有结点的键值小于该结点的键值;
其右子树中所有结点的键值大于等于该结点的键值;
其左右子树都是二叉搜索树。
所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。
给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。
输入格式:
输入的第一行给出正整数 N(≤1000)。随后一行给出 N 个整数键值,其间以空格分隔。
输出格式:
如果输入序列是对一棵二叉搜索树或其镜像进行前序遍历的结果,则首先在一行中输出 YES ,然后在下一行输出该树后序遍历的结果。数字间有 1 个空格,一行的首尾不得有多余空格。若答案是否,则输出 NO。
输入样例 1:
7
8 6 5 7 10 8 11
输出样例 1:
YES
5 7 6 8 11 10 8
输入样例 2:
7
8 10 11 8 6 7 5
输出样例 2:
YES
11 8 10 7 5 6 8
输入样例 3:
7
8 6 8 5 10 9 11
输出样例 3:
NO
思路: 先建树,然后求出这棵树的先序遍历结果与镜像先序遍历结果。若是先序遍历结果那就输出正常后序遍历结果,若是镜像遍历结果那就输出镜像后序遍历结果。
#include<string.h>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<set>
using namespace std;
typedef long long ll;
const int maxn = 1e3 + 10;
const int inf = 0x3f3f3f3f;
const ll INF = 1ll << 62;
const double PI = acos(-1);
const double eps = 1e-7;
const int mod = 998244353;
#define speed {ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); }
struct node
{
int value;
node *l, *r;
node(int value = 0, node *l = NULL, node *r = NULL) :value(value), l(l), r(r) {}
};
void buildtree(node *&root, int x)//建树
{
if (root == NULL)root = new node(x);
else
{
if (x >= root->value)buildtree(root->r, x);
if (x < root->value)buildtree(root->l, x);
}
}
int cnt,pre[maxn],expre[maxn],post[maxn];//分别是计步器、存储先序键值、存储镜像先序键值、存储后序键值
void preorder(node *root)//求先序
{
if(root!=NULL)
{
pre[cnt++]=root->value;
preorder(root->l);
preorder(root->r);
}
}
void expreorder(node *root)//求镜像先序
{
if(root!=NULL)
{
expre[cnt++]=root->value;
expreorder(root->r);//因为是镜像所以先访问右节点
expreorder(root->l);
}
}
void postorder(node *root)//求后序
{
if(root!=NULL)
{
postorder(root->l);
postorder(root->r);
post[cnt++]=root->value;
}
}
void expostorder(node *root)//求镜像后序
{
if(root!=NULL)
{
expostorder(root->r);
expostorder(root->l);
post[cnt++]=root->value;
}
}
void Free(node *root)//释放空间
{
if (root == NULL)return;
Free(root->l);
Free(root->r);
delete root;
}
int main()
{
int n,a[maxn];
scanf("%d",&n);
for(int i=0;i<n;i++)scanf("%d",&a[i]);//存储原先数组
node *root;
root =new node(a[0]);//给根节点赋初值
for(int i=1;i<n;i++)//建树
buildtree(root,a[i]);
cnt=0;
preorder(root);
cnt=0;
expreorder(root);
int f=1,ff=1;//如果是正常先序f=1,若是镜像先序ff=1;
for(int i=0;i<n;i++)
{
if(a[i]!=pre[i])f=0;
if(a[i]!=expre[i])ff=0;
}
if(f+ff==0)printf("NO\n");//若都不是输出NO
else
{
printf("YES\n");
cnt=0;
if(f==1)//如果是正常先序,那就输出正常后序
{
postorder(root);
for(int i=0;i<n;i++)
printf("%d%c",post[i]," \n"[i==n-1]);
}
else if(ff==1)//如果是镜像先序,那就输出镜像后序
{
expostorder(root);
for(int i=0;i<n;i++)
printf("%d%c",post[i]," \n"[i==n-1]);
}
}
Free(root);//释放空间
system("paues");
return 0;
}