题目重述
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
题解
恢复二叉树之后,反转二叉树,最后层次遍历即可。
C++ AC
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct node
{
int l;
int r;
};
node nds[35];
int xian[35],zhong[35];
//构造二叉树
int build(int i, int j, int k, int h)
{
int m=k;
int root = xian[i];
while(zhong[m]!=root)
m++;
if(m==k)
nds[root].l=-1;
else
nds[root].l=build(i+1,m-k+i,k,m-1);
//如果中序的最后一个是根节点,那说明还原后的右子树是空的
if(m==h)
nds[root].r=-1;
else
nds[root].r=build(m+j-h+1,j,m+1,h);
return root;
}
//二叉树层次遍历
void BFS(int u)
{
queue<int> q;
q.push(u);
while(!q.empty())
{
if(nds[q.front()].l!=-1)
{
q.push(nds[q.front()].l);
}
if(nds[q.front()].r!=-1)
{
q.push(nds[q.front()].r);
}
//格式控制
if(q.front()==u)
{
cout<<q.front();
}
else
{
cout<<" "<<q.front();
}
q.pop();
}
}
//交换节点
void swapTree(int root){
int tmp = nds[root].l;
nds[root].l = nds[root].r;
nds[root].r = tmp;
}
//反转二叉树
void invertBinaryTree(int root) {
if(root == -1)
return;
invertBinaryTree(nds[root].l);
invertBinaryTree(nds[root].r);
swapTree(root);
}
int main()
{
node nd;
nd.l=-1;
nd.r=-1;
int n;
cin>>n;
for(int i=0; i<n; i++)
{
nds[i]=nd;
}
for(int i=0; i<n; i++)
{
cin>>zhong[i];
}
for(int i=0; i<n; i++)
{
cin>>xian[i];
}
int root = build(0,n-1,0,n-1);
invertBinaryTree(xian[0]);
BFS(root);
return 0;
}