7-3 玩转二叉树(25 分)
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N
(≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
输出样例:
4 6 1 7 5 3 2
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<queue>
using namespace std;
int last[31];
typedef struct tree{
int data;
struct tree *lchild,*rchild;
}BiTree,*BiTode;
queue<BiTode> q;
BiTree* creattree(int *first,int *zhong,int n){
BiTree *tree;
if(n==0){
return NULL;
}
else{
tree=(struct tree*)malloc(sizeof(struct tree));
int i;
for(i=0;i<n;i++){
if(zhong[i]==first[0])
break;
}
tree->data=first[0];
tree->lchild=creattree(first+1,zhong,i);
tree->rchild=creattree(first+i+1,zhong+i+1,n-i-1);
return tree;
}
}
void change(BiTode tree){
if(tree==NULL)
return;
else{
BiTree *t;
t=tree->lchild;
tree->lchild=tree->rchild;
tree->rchild=t;
change(tree->lchild);
change(tree->rchild);
}
}
int cengci(BiTode tree,int last[]){
int i=0;
q.push(tree);
BiTode p=NULL;//新定义的p有指针的作用,不断的往下走。
while(!q.empty()){
p=q.front();
last[i++]=p->data;
q.pop();
if(p->lchild!=NULL){
q.push(p->lchild);
}
if(p->rchild!=NULL)
q.push(p->rchild);
}
return i;
}
int main(){
int n,i,j;
BiTree *tree;
scanf("%d",&n);
int first[31],zhong[31];
for(i=0;i<n;i++){
scanf("%d",&zhong[i]);
}
for(j=0;j<n;j++){
scanf("%d",&first[j]);
}
tree=creattree(first,zhong,n);
change(tree);
int end1=cengci(tree,last);
printf("%d",last[0]);
for(i=1;i<n;i++){
printf(" %d",last[i]);
}
}