给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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<cstdlib>
#include<queue>
using namespace std;
typedef struct TNode* PTree;
typedef struct TNode{
int data;
PTree Left;
PTree Right;
}Tree;
PTree BuildTree(int* pre, int* in, int n) {//根据先序以及中序遍历构建二叉树
if (n == 0)return NULL;
int m;
for (m = 0;in[m] != pre[0];m++);//找出左树的个数以及位置进行分隔
PTree T = (PTree)malloc(sizeof(Tree));
T->data = in[m];
T->Left = BuildTree(pre + 1, in, m);//递归的调用对左子树右子树分别构建
T->Right = BuildTree(pre + m + 1, in + m + 1, n - m - 1);
return T;
}
void Rever(PTree T) {//对已经构建好的树进行翻转
if (!T)return;
PTree temp = T->Left;
T->Left = T->Right;
T->Right = temp;
Rever(T->Left);
Rever(T->Right);
}
void Print(PTree T) {//层序遍历输出树
queue<PTree> q;
PTree p;
q.push(T);
int flag = 0;
while (!q.empty()) {
p = q.front();
q.pop();
if (flag != 0)cout << " ";
cout << p->data;
flag++;
if (p->Left)q.push(p->Left);
if (p->Right)q.push(p->Right);
}
}
int main() {
int n;
cin >> n;
int pre[35], in[35];
for (int i = 0;i < n;i++)
cin >> in[i];
for (int i = 0;i < n;i++)
cin >> pre[i];
PTree T = BuildTree(pre, in, n);
Rever(T);
Print(T);
return 0;
}