输入样例:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
输出样例:
4 6 1 7 5 3 2
思路
本题考察由前序中序获得完整二叉树并获得层序遍历
结果,其实并不是很难。
关键点有两个:
- 由前序中序建立二叉树(用链式结构存储较简单)
- 将建立的二叉树层序遍历,层序遍历时要逆序输出(可以考虑使用队列或栈)
#include<bits/stdc++.h>
using namespace std;
#define For(i,a,b) for(int i=a;i<b;i++)
struct node
{
int value;
node* l=NULL,*r=NULL;
};
node* BuildTree(int root,int l,int r,int pre[],int in[],int n)
{
if(l>r)return NULL;
node* newroot=new(node);
newroot->value=pre[root];
int i=l;
for(;i<n&&in[i]!=pre[root];i++);
newroot->l=BuildTree(root+1,l,i-1,pre,in,n);
newroot->r=BuildTree(root+i-l+1,i+1,r,pre,in,n);
return newroot;
}
// void travel(node* root)
// {
// if(root==NULL)return;
// travel(root->l);
// cout<<root->value<<" ";
// travel(root->r);
// }
void BFS(node* root)
{
int cnt=0;
if(root==NULL)return;
queue<node*>q;
q.push(root);
while(!q.empty())
{
auto tmp=q.front();
if(cnt==0)
cout<<tmp->value;
else cout<<" "<<tmp->value;
q.pop();
if(tmp->r)
{
q.push(tmp->r);
}
if(tmp->l)
{
q.push(tmp->l);
}
cnt++;
}
}
int main()
{
int n;
cin>>n;
int in[n],pre[n];
For(i,0,n)
cin>>in[i];
For(i,0,n)
cin>>pre[i];
node* root=BuildTree(0,0,n-1,pre,in,n);
BFS(root);
return 0;
}