给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
该题与 L2-006 基本一模一样 不同的就是 先将右孩子放入队列。
L2-006:http://blog.csdn.net/yf224/article/details/79152281
#include<cstdio>
#include<queue>
using namespace std;
int n;
int bef[100];//数组开大点 开始35出现段错误
int mid[100];
struct node{
int l;
int r;
}tree[100];
int build(int la, int ra, int lb, int rb){//la,ra代表中序,lb,rb代表前序
if(la > ra)return -1;
int root = bef[lb],p1,p2;
p1 = la;
while(mid[p1] != root) p1++;
p2 = p1-la;
tree[root].l = build(la, p1-1, lb+1, lb+p2);
tree[root].r = build(p1+1, ra, lb+p2+1, rb);
return root;
}
void bfs(int a){
queue<int>p;
p.push(a);
int flag=0;
while(!p.empty()){
int f = p.front();
p.pop();
if(flag) printf(" ");
printf("%d",f);
flag=1;
if(tree[f].r!=-1){
p.push(tree[f].r);
}
if(tree[f].l!=-1){
p.push(tree[f].l);
}
}
}
int main(){
scanf("%d", &n);
for(int i = 0; i < n; i++)scanf("%d",&mid[i]);
for(int i = 0; i < n; i++)scanf("%d",&bef[i]);
build(0, n-1, 0, n-1);
bfs(bef[0]);
return 0;
}