//以下代码仅供参考,有什么可以优化的请指教指教 //联系QQ 344590697 #include <stdio.h> #include <malloc.h> int toprc=-1,tobase=-1;; int before[10000],nowing[10000]; int n; int a=0; int AP=0; int now=1; int AAAA=0; typedef struct btree { int date; struct btree *lchrild,*rchrild; }BT; typedef struct RootCollection { int root[10000]; int rootI[10000]; int top; int topI; }RC; RC rc; BT *btrc[2000]; BT *creat(); BT *RebuildBT(BT *T); int Check();//检验是否是左子树 或 右子树 void Push(int a);//压入前序中当前节点在中序中的位置 void PUSH(int root);//压入前序当前节点数据 void LaverTrave(BT *T);//层序遍历 void LateTrave(BT *T);//后续遍历 void Push(int a) { if(rc.topI<10000) { rc.topI++; rc.rootI[rc.topI]=a; } else printf("栈已满/n"); } void PUSH(int root) { if(rc.top<10000) { rc.top++; rc.root[rc.top]=root; } else printf("栈已满/n"); } BT *creat() { BT *bitree; bitree=(BT*) malloc (sizeof(BT)); bitree->date=before[0]; bitree->lchrild = NULL; bitree->rchrild = NULL; PUSH(before[0]); Push(a); return bitree; } int Check() { int anwser=-1; int i; int rt=0; int j; AP=rc.topI; for(i=0;i<n;i++)///新的节点入栈 if(nowing[i]==before[now]) { Push(i); break; } if(rc.rootI[rc.topI]<rc.rootI[rc.topI-1])///判断左子树 anwser=0; else for(i=rc.topI-1;i>=0;i--)//判断右子树 { if(rc.rootI[rc.topI]<rc.rootI[i]) { for(j=i+1;j<rc.topI-1;j++) if(rc.rootI[j]>rc.rootI[j+1]) break; AP=j; toprc=AP; rc.rootI[AP+1]=rc.rootI[rc.topI]; rc.topI=AP+1; rc.top=AP+1; anwser=1; break; } else if(rc.rootI[i]==AAAA) { AAAA=rc.rootI[rc.topI]; anwser=1; toprc=i; rc.rootI[i+1]=rc.rootI[rc.topI]; rc.topI=i+1; rc.top=i+1; } } return anwser; } BT *RebuildBT(BT *T) { BT *t; int anwser; toprc++; btrc[toprc]=T; while(now<n) { anwser=Check(); if(!anwser) { t=btrc[toprc]; t->lchrild=(BT *) malloc (sizeof(BT)); t->lchrild->date=before[now]; T=btrc[toprc]; PUSH(before[now]); now++; toprc++; btrc[toprc]=T->lchrild; T=btrc[toprc]; T->lchrild = NULL; T->rchrild = NULL; } if(anwser==1) { t=btrc[toprc]; t->rchrild=(BT *) malloc (sizeof(BT)); t->rchrild->date=before[now]; T=btrc[toprc];PUSH(before[now]); now++; toprc++; btrc[toprc]=T->rchrild; T=btrc[toprc]; T->lchrild = NULL; T->rchrild = NULL; } } return btrc[0]; } void LaverTrave(BT *T) { tobase++; toprc++; btrc[toprc]=T; while(tobase<=toprc) { printf("%d ", btrc[tobase]->date); if(btrc[tobase]->lchrild!=NULL) { toprc++; btrc[toprc]=btrc[tobase]->lchrild; } if(btrc[tobase]->rchrild!=NULL) { toprc++; btrc[toprc]=btrc[tobase]->rchrild; } tobase++; } } void LateTrave(BT *T) { if(T==NULL) return ; else { LateTrave(T->lchrild); LateTrave(T->rchrild); printf("%d ",T->date); } } void main () { BT *bitree; int i; scanf("%d",&n); rc.top=-1; rc.topI=-1; for(i=0;i<n;i++) scanf("%d",&before[i]); for(i=0;i<n;i++) { scanf("%d",&nowing[i]); if(nowing[i]==before[0]) { a=i; AAAA=a; } } bitree=creat(); bitree=RebuildBT(bitree); toprc=-1; LaverTrave(bitree); printf("/n");// LateTrave(bitree);//后续遍历 }