对于二叉搜索树,我们规定任一结点的左子树仅包含严格小于该结点的键值,而其右子树包含大于或等于该结点的键值。如果我们交换每个节点的左子树和右子树,得到的树叫做镜像二叉搜索树。
现在我们给出一个整数键值序列,请编写程序判断该序列是否为某棵二叉搜索树或某镜像二叉搜索树的前序遍历序列,如果是,则输出对应二叉树的后序遍历序列。
输入格式:
输入的第一行包含一个正整数N(≤1000),第二行包含N个整数,为给出的整数键值序列,数字间以空格分隔。
输出格式:
输出的第一行首先给出判断结果,如果输入的序列是某棵二叉搜索树或某镜像二叉搜索树的前序遍历序列,则输出YES
,否侧输出NO
。如果判断结果是YES
,下一行输出对应二叉树的后序遍历序列。数字间以空格分隔,但行尾不能有多余的空格。
输入样例1:
7
8 6 5 7 10 8 11
输出样例1:
YES
5 7 6 8 11 10 8
输入样例2:
7
8 6 8 5 10 9 11
输出样例2:
NO
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct node
{
struct node *lchild;
struct node *rchild;
int data;
}tree;
int flag1=0,flag2=0;
tree *findtree(int pre[],int n)
{
if(!n)
{
return NULL;
}
tree *T;
T=(tree *)malloc(sizeof(tree));
T->data =*pre;
int i,j;
for(i=1;i<n;i++)
{
if(pre[i]>=T->data )
break;
}
for(j=i;j<n;j++)
{
if(pre[j]<T->data )
{
flag1=1;
return NULL;
}
}
T->lchild =findtree(pre+1,i-1);
T->rchild =findtree(pre+i,n-i);
return T;
}
tree *findmtree(int pre[],int n)
{
if(!n)
{
return NULL;
}
tree *T;
T=(tree *)malloc(sizeof(tree));
T->data =*pre;
int i,j;
for(i=1;i<n;i++)
{
if(pre[i]<T->data )
break;
}
for(j=i;j<n;j++)
{
if(pre[j]>=T->data )
{
flag2=1;
return NULL;
}
}
T->lchild =findmtree(pre+1,i-1);
T->rchild =findmtree(pre+i,n-i);
return T;
}
int flag=0;
void lprint(tree *T)
{
if(T)
{
lprint(T->lchild );
lprint(T->rchild );
if(!flag)
flag=1;
else
cout<<' ';
printf("%d",T->data );
}
}
int main()
{
int n,i;
int pre[1005];
cin>>n;
for(i=0;i<n;i++)
{
scanf("%d",&pre[i]);
}
tree *T=NULL,*Tm=NULL;
//T=(tree*)malloc (sizeof(T));
//Tm=(tree*)malloc(sizeof(Tm));
T=findtree(pre,n);
Tm=findmtree(pre,n);
if(T&&!flag1)
{
cout<<"YES"<<endl;
lprint(T);
cout<<endl;
}
else if(Tm&&!flag2)
{
cout<<"YES"<<endl;
lprint(Tm);
cout<<endl;
}
else
cout<<"NO"<<endl;
return 0;
}