给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
int f[35],m[35];
int n;
typedef struct Node{
int data;
struct Node *lch,*rch;
}Node,*btree;
void setup(int b1,int e1,int b2,int e2,btree &T){
if(b1>e1){
T = NULL;
return;
}
T = new Node;
T->data = f[b1];
for(int i=b2;i<=e2;i++){
if(m[i]==f[b1]){
setup(b1+1,b1+i-b2,b2,i-1,T->lch);
setup(b1+i-b2+1,e1,i+1,e2,T->rch);
}
}
}
void bfs(btree &T){
queue<btree> q;
if(T==NULL){
return ;
}
q.push(T);
printf("%d",T->data);
while(q.empty()==false){
btree temp = q.front();
q.pop();
if(temp->rch!=NULL){
printf(" %d",temp->rch->data);
q.push(temp->rch);
}
if(temp->lch!=NULL){
printf(" %d",temp->lch->data);
q.push(temp->lch);
}
}
}
void first(btree T){
if(T){
printf("%d ",T->data);
first(T->lch);
first(T->rch);
}
}
int main()
{
cin>>n;
for(int i=0;i<n;i++){
cin>>m[i];
}
for(int i=0;i<n;i++){
cin>>f[i];
}
btree T = NULL;
setup(0,n-1,0,n-1,T);
//first(T);
bfs(T);
}