PAT乙级的一道题目,题目描述:
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
原文链接:https://www.patest.cn/contests/gplt/L2-011
其实就是关于二叉树重建的问题。交换非叶子节点的左右子树其实就是让我们从右向左层序遍历输出这个二叉树,不过有一个坑就是这里的输入是先输入中序遍历的数据,然后才是前序遍历的数据。这里注意一下就行了。如果对二叉树的重建的思想不熟的小伙伴可以看看这篇文章:http://blog.csdn.net/Hacker_ZhiDian/article/details/60770262
好了,下面给出 AC 代码:
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 10110;
int pre[N];
int in[N];
int pos;
struct Node { // 储存二叉树节点的信息
int w;
int l;
int r;
};
Node node[N];
void input(int a[], int n) {
for(int i = 0; i < n; i++) {
cin >> a[i];
}
}
// 递归重建二叉树
void rec(int l, int r, int n) {
if(l >= r) {
node[n].w = -1;
return ;
}
int root = pre[pos++];
node[n].w = root;
node[n].l = 2 * n; // 左子节点下标
node[n].r = 2 * n + 1; // 右子节点下标
int mid = find(in, in+r, root) - in;
rec(l, mid, 2*n); // 重建左子树
rec(mid+1, r, 2*n+1); // 重建右子树
}
// 从右向左层序遍历二叉树,使用的是 C++ STL 提供的队列模板
void print() {
queue<int> que;
que.push(1);
int n;
while(!que.empty()) {
n = que.front();
que.pop();
if(node[n].w != -1) {
if(n != 1) {
cout << " ";
}
cout << node[n].w;
que.push(node[n].r); // 因为是从右向左,所以先添加右子节点
que.push(node[n].l);
}
}
cout << endl;
}
int main() {
int n;
cin >> n;
for(int i = 1; i < N; i++) {
node[i].w = -1;
}
input(in, n);
input(pre, n);
rec(0, n, 1);
print();
return 0;
}
好了,如果博客中有什么不正确的地方,请多多指点。如果觉得我写的不错,请点个赞支持我吧。
谢谢观看。。。