给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N=1e5+7;
struct node
{
int data;
node *left,*right;
};
int n;
int qian[N],zhong[N];
node *create(int q,int z,int len)//创建树
{
node *T;
if(len<=0) T=NULL;
else
{
T=(node *)malloc(sizeof(node));
T->data=qian[q];
int i;
for(i=0; zhong[z+i]!=qian[q]; i++);
T->left=create(q+1,z,i);
T->right=create(q+i+1,z+i+1,len-i-1);
}
return T;
}
node *fanzhuan(node *T)//翻转树
{
node *t;
if(T)
{
if(T->left!=NULL||T->right!=NULL)
{
t=T->left;
T->left=T->right;
T->right=t;
}
fanzhuan(T->left);
fanzhuan(T->right);
}
return T;
}
void _printf(node *T)//输出树
{
node *q[N],*p;
int l=0,r=0,cnt=0;
if(T)
{
q[r++]=T;
while(l!=r)
{
p=q[l++];
cnt++;
if(cnt==n) printf("%d\n",p->data);
else printf("%d ",p->data);
if(p->left!=NULL) q[r++]=p->left;
if(p->right!=NULL) q[r++]=p->right;
}
}
}
//void _printf(node *T)//用队列输出树
//{
// queue <node*> q;
// q.push(T);
// int cnt=0;
// while(!q.empty())
// {
// node *now=q.front();
// q.pop();
// cnt++;
// if(cnt==n) printf("%d\n",now->data);
// else printf("%d ",now->data);
// if(now->left!=NULL) q.push(now->left);
// if(now->right!=NULL) q.push(now->right);
// }
//}
int main()
{
scanf("%d",&n);
for(int i=0; i<n; i++) scanf("%d",&zhong[i]);
for(int i=0; i<n; i++) scanf("%d",&qian[i]);
node *T=create(0,0,n);
T=fanzhuan(T);
_printf(T);
return 0;
}