题目详情 - L2-011 玩转二叉树 (25 分) (pintia.cn)
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
思路:按中序和前序建树,由于要镜像二叉树(左子树 > 根 > 右子树),所以直接在建树的过程中交换赋值就行了,然后就是bfs层序遍历输出。
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
const int N = 40;
typedef struct Node* Tree;
struct Node{
int data;
Tree l,r;
Node(int _data){
data = _data;
l = r = nullptr;
}
};
int a[N],b[N];
Tree build(int l1,int l2,int sz){
if(sz <= 0) return nullptr;
Tree tree = new Node(b[l2]);
int k = 0;
while(a[l1+k] != b[l2]) k++;
tree->r = build(l1,l2+1,k);
tree->l = build(l1+k+1,l2+k+1,sz-(k+1));
return tree;
}
int main(){
int n;
cin>>n;
for(int i = 0; i < n; i++) cin>>a[i];
for(int i = 0; i < n; i++) cin>>b[i];
Tree root = build(0,0,n);
queue<Tree> que;
que.push(root);
while(que.size()){
int sz = que.size();
for(int i = 0; i < sz; i++){
auto tmp = que.front();
que.pop();
if(tmp->l) que.push(tmp->l);
if(tmp->r) que.push(tmp->r);
cout<<tmp->data;
if(que.size()) cout<<' ';
}
}
return 0;
}