题目分析:这里牵扯到一类问题,就是已知二叉树的两种遍历顺序,去求另外一种遍历的序列,这类问题共可以分为下面这2种:(1)已知前序和中序,求后序或层序(2)已知后序和中序求前序或层序。如果已知前序和后序则不能求出其他遍历序列,这里就拿这个题来说一下怎么解决这种问题,其实会一种,其他的就都会了。
这个题给出了后序和中序序列,根据他们的性质,我们可以知道后序的最后一个元素一定是这颗二叉树的根,所以我们上来就能找到根,然后去中序里面找这个根所在的位置,在中序中,根左边的就是左子树,根右边的就是右子树,因此我们就可以求出左右子树中节点的个数,然后在后序中找到左子树部分和右子树部分,递归去创建就好了,树建好了后,遍历就非常简单了,所以就不多说了。
上代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
const int N=35;
struct node{
int data;
struct node*l;
struct node*r;
};
int post[N],in[N];
int n;
struct node* createtree(int postl,int postr,int inl,int inr)
{
if(postl>postr)//这里要注意,不然很容易死循环
return NULL;
int k;
for(k=1;k<=n;k++)
if(in[k]==post[postr])//在中序中找到根的位置
break;
int numleft=k-inl;//得到左子树中节点的数量
struct node* root=new node;
root->data=post[postr];
root->l=createtree(postl,postl+numleft-1,inl,k-1);
root->r=createtree(postl+numleft,postr-1,k+1,inr);
return root;
}
void bfs(struct node* root)//求层序遍历的结果
{
queue<struct node*>q;
q.push(root);
bool flag=false;
while(q.size())
{
auto t=q.front();
q.pop();
if(!flag)
cout<<t->data,flag=true;
else
cout<<" "<<t->data;
if(t->l)
q.push(t->l);
if(t->r)
q.push(t->r);
}
return ;
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
cin>>post[i];
for(int i=1;i<=n;i++)
cin>>in[i];
struct node *root=createtree(1,n,1,n);
bfs(root);
return 0;
}