一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,
- 其左子树中所有结点的键值小于该结点的键值;
- 其右子树中所有结点的键值大于等于该结点的键值;
- 其左右子树都是二叉搜索树。
所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。
给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。
输入格式:
输入的第一行给出正整数 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
题解:
判断给出的插入序列是否为建立的二叉搜索树的前序遍历,如果是,则输入二叉搜索树的后序遍历,不是再判断是否为二叉搜索树镜像的前序遍历,如果是,则输出二叉搜索树镜像的后序遍历,二者都不是则输出NO。
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
struct node*left;
struct node*right;
} tree;
tree*creat(tree*root,int x)//建立搜索二叉树
{
if(!root)
{
root=new node;
root->data=x;
root->right=root->left=NULL;
}
else
{
if(x<root->data)
{
root->left=creat(root->left,x);
}
else
{
root->right=creat(root->right,x);
}
}
return root;
}
int first1[1010];
int first2[1010];
int flag1=0;
int flag2=0;
void first1_tree(tree*root)//二叉搜索树的前序遍历
{
if(root)
{
first1[flag1]=root->data;
flag1++;
first1_tree(root->left);
first1_tree(root->right);
}
}
void first2_tree(tree*root)//二叉搜索树的镜像的前序遍历
{
if(root)
{
first2[flag2]=root->data;
flag2++;
first2_tree(root->right);
first2_tree(root->left);
}
}
int f=0;
void last1_tree(tree*root)//二叉搜索树的后序遍历
{
if(root)
{
last1_tree(root->left);
last1_tree(root->right);
if(f==0)
{
printf("%d",root->data);
f=1;
}
else
{
printf(" %d",root->data);
}
}
}
void last2_tree(tree*root)//二叉搜索树镜像的后序遍历
{
if(root)
{
last2_tree(root->right);
last2_tree(root->left);
if(f==0)
{
printf("%d",root->data);
f=1;
}
else
{
printf(" %d",root->data);
}
}
}
int main()
{
int n;
tree*root;
root=NULL;
scanf("%d",&n);
int num[1010];
for(int i=0; i<n; i++)
{
int x;
scanf("%d",&x);
num[i]=x;
root=creat(root,x);
}
first1_tree(root);
first2_tree(root);
int fflag1=0;
int fflag2=0;
for(int i=0; i<n; i++)
{
if(first1[i]!=num[i])
{
fflag1=1;
}
}
for(int i=0; i<n; i++)
{
if(first2[i]!=num[i])
{
fflag2=1;
}
}
if(fflag1==1&&fflag2==1)
{
printf("NO\n");
}
else
{
printf("YES\n");
if(fflag1==0)
{
last1_tree(root);
printf("\n");
}
else
{
last2_tree(root);
printf("\n");
}
}
return 0;
}