一.问题描述:
输入一个键值序列,判断该序列是否为某棵二叉搜索树或某镜像二叉搜索树的前序遍历序列,如果是,则输出对应二叉树的后序遍历序列。
二.思路:
1.用数组存储输入的键值序列a,a[0]是二叉搜索树的根(Bintree BuildBST(int temp);),(用temp的原因是为了不改变a[],因为后面还要用它 与 二叉搜索树和镜像二叉搜索树的先序遍历比较)再通过遍历数组的每下一个值,插入这个元素,递归创建二叉搜索树。
2.分别先序遍历二叉搜索树、镜像二叉搜索树。并用数组保存其值(因为要与输入序列a[]做比较)
镜像二叉搜索树:交换二叉搜索树每个节点的左子树和右子树。(与二叉搜索树唯一区别:遍历顺序从先左后右 变成 对二叉搜索树先右后左 的遍历。)
1)先序遍历:根、右子树、左子树。
2)后序遍历:右子树、左子树、根。
3.若a[]与二叉搜索树、镜像二叉搜索树的先序遍历相同,则输出对应树的后序遍历。
三.代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 1111
typedef struct LNode *Position;//定义区别链表
typedef Position Bintree;
struct LNode{
int Data;
Bintree Left;
Bintree Right;
};
int a[MAXN]={0};
Bintree BuildBST(int temp)
{
Bintree BST;
BST = (Bintree)malloc(sizeof(struct LNode));
BST->Data = temp;
BST->Left = NULL;
BST->Right = NULL;
return BST;
}
void Insert(Bintree BST,int temp) //创建二叉搜索树
{
if(BST->Data >temp){
if(BST->Left ==NULL){
Bintree P = (Bintree)malloc(sizeof(struct LNode));
P->Data =temp;
P->Left =NULL;
P->Right =NULL;
BST->Left = P;
}
else Insert(BST->Left ,temp);
}
else{
if(BST->Right ==NULL){
Bintree P = (Bintree)malloc(sizeof(struct LNode));
P->Data =temp;
P->Left =NULL;
P->Right =NULL;
BST->Right = P;
}
else Insert(BST->Right ,temp);
}
}
int qushuPre[MAXN]={0};
int num_Preorder=0;
void Preorder(Bintree BST)
{
if(BST!=NULL)
{
qushuPre[num_Preorder++]=BST->Data;
Preorder(BST->Left);
Preorder(BST->Right);
}
}
int Mi_qushuPre[MAXN]={0};//镜像二叉树的先序排列
int Mi_num_Preorder=0;
void Mi_Preorder(Bintree BST)
{
if(BST!=NULL)
{
Mi_qushuPre[Mi_num_Preorder++]=BST->Data;
Mi_Preorder(BST->Right);//因为镜像二叉树左右子树交换,所以要先遍历右子树
Mi_Preorder(BST->Left);
}
}
int qushuPost[MAXN]={0};
int num_Postorder=0;
void Postorder(Bintree BST)
{
if(BST!=NULL)
{
Postorder(BST->Left);
Postorder(BST->Right);
qushuPost[num_Postorder++]=BST->Data;
}
}
int Mi_qushuPost[MAXN]={0};//镜像二叉树的后序排列
int Mi_num_Postorder=0;
void Mi_Postorder(Bintree BST)
{
if(BST!=NULL)
{
Mi_Postorder(BST->Right);//先遍历右子树
Mi_Postorder(BST->Left);
Mi_qushuPost[Mi_num_Postorder++]=BST->Data;
}
}
int main()
{
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++) scanf("%d",&a[i]);
int temp=a[0];
Bintree BST = BuildBST(temp);
for(i=1;i<n;i++) Insert(BST,a[i]);
Preorder(BST);
Mi_Preorder(BST);
int flag = 1;//判断先序遍历是否为二叉搜索树
for(i=0;i<num_Preorder;i++){
if(a[i]!=qushuPre[i]){
flag = 0;
break;
}
}
if(flag){
printf("YES\n");
Postorder(BST);
printf("%d",qushuPost[0]);
for(i=1;i<num_Postorder;i++){
printf(" %d",qushuPost[i]);
}
return 0;
}
flag = 1;//判断先序遍历是否为镜像二叉搜索树
for(i=0;i<Mi_num_Preorder;i++){
if(a[i]!=Mi_qushuPre[i]){
flag = 0;
break;
}
}
if(flag){
printf("YES\n");
Mi_Postorder(BST);
printf("%d",Mi_qushuPost[0]);
for(i=1;i<Mi_num_Postorder;i++){
printf(" %d",Mi_qushuPost[i]);
}
return 0;
}
printf("NO\n");
return 0;
}