因为后序最后访问的一定是根节点,所以我们可以令root为后序中当前根节点的下标,通过找到post[root]在中序中的位置,可以将中序的左子树与右子树划分出来。start与end划定子树的节点在中序中的范围,递归打印前序序列,出口为start>end。
#include<bits/stdc++.h>
using namespace std;
int in[50],post[50];
int n;
int build(int root,int start,int end){
if(start>end) return 0;
int i=start;
while(in[i]!=post[root]) i++;
printf("%d ",post[root]);
build(root-end+i-1,start,i-1);
build(root-1,i+1,end);
}
int main()
{
int i;
cin>>n;
for(i=0;i<n;i++) cin>>in[i];
for(i=0;i<n;i++) cin>>post[i];
build(n-1,0,n-1);
return 0;
}
建树:
#include<bits/stdc++.h>
using namespace std;
int pre[35];
int k=0;
void build(int *last,int *in,int size)
{
if(size<=0) return;
int temp=h[size-1];
pre[k++]=temp;
int index=0;
while(index<size)
{
if(in[index]==temp) break;
index++;
}
pre(last,in,index);
pre(last+index,in+index+1,size-index-1);
}
int main()
{
int n;
scanf("%d",&n);
int in[35],last[35];
for(int i=0;i<n;i++) scanf("%d",&in[i]);
for(int i=0;i<n;i++) scanf("%d",&last[i]);
pre(last,in,n);
for(int i=0;i<n;i++) printf(" %d",pre[i]);
return 0;
}