标签:
D / / B E / \ / \ A C G / / F
DBACEGF ABCDEFG BCAD CBAD
ACBFGED CDAB
#include<cstdio> #include<cstring> #include<cstdlib> struct node { char value; node *leftchild; node *rightchild; }; node *newnode(char c) { node *p=(node *)malloc(sizeof(node)); p->value=c; p->leftchild=p->rightchild=NULL; return p; } node *rebuild(char *pre,char *in,int len) { if(len==0) return NULL; node *p=newnode(pre[0]); int i; for(i=0;i<len && in[i]!=pre[0];i++); int leftlen=i; int rightlen=len-i-1; if(leftlen>0) p->leftchild=rebuild(pre+1,in,leftlen); if(rightlen>0) p->rightchild=rebuild(pre+1+leftlen,in+leftlen+1,rightlen); return p; } void pos(node *p) { if(p==NULL) return; pos(p->leftchild); pos(p->rightchild); printf("%c",p->value); } int main() { char preorder[30],inorder[30]; while(scanf("%s%s",&preorder,&inorder)!=EOF) { int len=strlen(preorder); node *newtree=rebuild(preorder,inorder,len); pos(newtree); printf("\n"); } return 0; }
标签:
原文地址:http://blog.csdn.net/zuguodexiaoguoabc/article/details/44002599