7-4 玩转二叉树 分数 25
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n; // 节点数
int pre[N]; // 先序遍历得到的的序列
int mid[N]; // 中序遍历得到的的序列
struct node
{
int data; //节点的数据
node *l, *r; //左孩子,右孩子
};
node *build(int len, int *pre, int *mid) //建树
{
node *root = new node;
if (!len)
return NULL; // 返回空节点
root->data = pre[0]; // pre[0]为根节点
int i;
for (i = 0; i < len; i++)
{
if (mid[i] == pre[0]) // 在中序遍历中找到根节点
break;
}
root->l = build(i, pre + 1, mid); // 建立左子树
root->r = build(len - i - 1, pre + i + 1, mid + i + 1); // 建立右子树
return root;
}
void cengxu(node *root)//层序遍历,从右往左遍历
{
bool flag = 0;
queue<node *> q;
q.push(root);
while (q.size())
{
node *top = q.front();
if (flag)
cout << " " << top->data;
else
{
cout << top->data;
flag = 1;
}
q.pop();
//先放右孩子,再放左孩子
if (top->r)
q.push(top->r);
if (top->l)
q.push(top->l);
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
cin >> mid[i];
for (int i = 0; i < n; i++)
cin >> pre[i];
node *root = build(n, pre, mid);
cengxu(root);
return 0;
}