对于二叉搜索树,我们规定任一结点的左子树仅包含严格小于该结点的键值,而其右子树包含大于或等于该结点的键值。如果我们交换每个节点的左子树和右子树,得到的树叫做镜像二叉搜索树。
现在我们给出一个整数键值序列,请编写程序判断该序列是否为某棵二叉搜索树或某镜像二叉搜索树的前序遍历序列,如果是,则输出对应二叉树的后序遍历序列。
输入格式:
输入的第一行包含一个正整数 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<vector>
#include<stdio.h>
using namespace std;
vector<int>tree;
int node,array[1024],i;
void positive(int father,int right){
int treel=father+1,treer=right;
while(treel<=right&&array[treel]<array[father])treel++;
while(treer>father&&array[treer]>=array[father])treer--;
if(treel-treer!=1)return;
positive(father+1,treer);
positive(treel,right);
tree.push_back(array[father]);
}
void verso(int father,int right){
int treel=father+1,treer=right;
while(treel<=right&&array[treel]>=array[father])treel++;
while(treer>father&&array[treer]<array[father])treer--;
if(treel-treer!=1)return;
verso(father+1,treer);
verso(treel,right);
tree.push_back(array[father]);
}
int main(){
scanf("%d",&node);
for(i=0;i<node;i++)scanf("%d",array+i);
positive(0,node-1);
if(tree.size()==node){
printf("YES\n");
for(i=0;i<node;i++){
if(i)printf(" ");
printf("%d",tree[i]);
}
}
else{
tree.empty();
verso(0,node-1);
if(tree.size()==node){
printf("YES\n");
for(i=0;i<node;i++){
if(i)printf(" ");
printf("%d",tree[i]);
}
}
else printf("NO");
}
return 0;
}