题目:https://dsa.cs.tsinghua.edu.cn/oj/problem.shtml?id=1146
现在有先序序列和后序序列
把先序序列用链表串起来,然后利用后序序列重排成中序序列,然后输出。
先序 弄成链表 p-> L……
-> R……
后序 放到数组 post[1-n] ……L
……R
p
我们要把p插到R的前面,R的值可以通过后序数组post[p的下标-1]获得,设置一个跟进标志c=lo,用一个指针指向p,不断后移,c不断+1
这样,把p插到R前,c也就移到R处,也就是lo到c-1即为左边的长度。c到hi-1即为右边的长度,初始lo为1,hi为n。
递归基为hi-lo<2.(因为是真二叉树,每个结点要么是叶子结点度为0,要么度为2,所以至少有三个元素我们才重排)
然后递归地处理左边与右边,然后就把先序序列重排成中序序列了,然后依次输出即可。
代码如下:
#include <iostream>
#include<cstdio>
using namespace std;
const int MAX=4000001;
struct Bnode{
int a;
Bnode *next;
};
int post[MAX];
void rebuild(Bnode *p,int lo,int hi){
if(hi-lo<2)return;
int c=lo;
int r=post[hi-1];
Bnode* h=p;
Bnode* q=p->next;
p=q;
while(p->next->a!=r){
p=p->next;
c++;
}
h->next=q->next;
q->next=p->next;
p->next=q;
rebuild(h,lo,c-1);
rebuild(q,c,hi-1);
}
int main()
{
int n,pr;
scanf("%d",&n);
Bnode *head;
head=new Bnode;
Bnode *p,*q;
head->a=0;
head->next=NULL;
p=head;
for(int i=1;i<=n;i++){
scanf("%d",&pr);
q=new Bnode;
q->a=pr;
q->next=NULL;
p->next=q;
p=q;
}
for(int i=1;i<=n;i++){
scanf("%d",&post[i]);
}
rebuild(head,1,n);
p=head->next;
while(p){
printf("%d",p->a);
p=p->next;
if(p)printf(" ");
else printf("\n");
}
return 0;
}