9度1078 前序和中序建二叉树
九度1078 前序和中序建二叉树
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct Node{ char data; struct Node *lc; struct Node *rc; }node; node *T; char a[30],b[30]; node* PreInCre(int m1,int m2,int h1,int h2) { node *root; int llen,rlen,i; root=(node*)malloc(sizeof(node)); root->data=a[m1]; for(i=h1;b[i]!=root->data;i++); llen=i-h1; rlen=h2-i; if(llen) root->lc=PreInCre(m1+1,m1+llen,h1,h1+llen-1); else root->lc=NULL; if(rlen) root->rc=PreInCre(m2-rlen+1,m2,h2-rlen+1,h2); else root->rc=NULL; return root; } PostOrder(node *BT) { if(BT!=NULL) { PostOrder(BT->lc); PostOrder(BT->rc); printf("%c",BT->data); } } int main() { int lena; while(scanf("%s",a)!=EOF) { scanf("%s",b); lena=strlen(a); T=PreInCre(0,lena-1,0,lena-1); PostOrder(T); printf("\n"); } return 0; }