给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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<queue>
using namespace std;
typedef struct Tree{
int data;
Tree* left;
Tree* right;
};
Tree* creat(int pre[],int in[],int n){
int i;
if(n<=0){
return NULL;
}
Tree* root=(Tree*)malloc(sizeof(Tree));
root->data=pre[0];
for(i=0;in[i]!=pre[0];i++);
root->left=creat(pre+1,in,i);
root->right=creat(pre+i+1,in+i+1,n-i-1);
return root;
}
void levelTraverse(Tree* T){
queue<Tree*> q;
cout<<T->data;
q.push(T);
while(!q.empty()){
Tree* temp=q.front();
q.pop();
if(temp->left!=NULL){
cout<<" "<<temp->left->data;
q.push(temp->left);
}
if(temp->right!=NULL){
cout<<" "<<temp->right->data;
q.push(temp->right);
}
}
}
void bk(Tree* T){
queue<Tree*> q;
q.push(T);
while(!q.empty()){
Tree* temp=q.front();
q.pop();
if(temp->left!=NULL){
q.push(temp->left);
}
if(temp->right!=NULL){
q.push(temp->right);
}
Tree* te;
te=temp->left;
temp->left=temp->right;
temp->right=te;
}
}
int main(){
int n;
cin>>n;
int s1[40],s2[40];
for(int i=0;i<n;i++){
cin>>s1[i];
}
for(int i=0;i<n;i++){
cin>>s2[i];
}
Tree* root=creat(s2,s1,n);
bk(root);
levelTraverse(root);
return 0;
}