根據先序和中序構建二叉樹
阿新 • • 發佈:2019-02-17
#include<bits/stdc++.h> using namespace std; typedef struct node { char data; struct node *lc,*rc; }node,*link; char pre[1005],in[1005]; link creat(char *pre,char *in,int p1,int p2,int i1,int i2) { link bt=new node; bt->data=pre[p1]; bt->lc=NULL; bt->rc=NULL; int pos=i1; while(in[pos]!=pre[p1]) pos++; int children=pos-i1; if(pos>i1) bt->lc=creat(pre,in,p1+1,p1+children,i1,pos-1); if(pos<i2) bt->rc=creat(pre,in,p1+children+1,p2,pos+1,i2); return bt; } void laorder(link L)//後序遍歷輸出 { if(L) { laorder(L->lc); laorder(L->rc); printf("%c ",L->data); } } int main() { scanf("%s",pre); scanf("%s",in); int n=strlen(pre); link L; L=creat(pre,in,0,n-1,0,n-1); laorder(L); printf("\n"); return 0; }