标签:des style blog io ar color os sp for
2 abdegcf dbgeafc xnliu lnixu
dgebfca abcdefg linux xnuli
借鉴的代码:
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct tree { char data; struct tree *l,*r; }BinTree; BinTree *creat(char *pre, char *in, int len) { int k; if(len<=0) return NULL; BinTree *head; head=(BinTree*)malloc(sizeof(BinTree)); head->data=*pre; char *p; for(p=in;p!=NULL;p++) if(*p==*pre) break;// 在中序遍历的序列中得到与先序相同的节点 k=p-in; head->l=creat(pre+1,in,k);//递归得到左子树 head->r=creat(pre+k+1,p+1,len-k-1);//得到右子树 return head; } void postorder(BinTree *t) { if(t) { postorder(t->l); postorder(t->r); printf("%c",t->data); } } void lorder(BinTree *t) { int front=0,rear=1; BinTree *q[100]; q[0]=t; while(front<rear) { if(q[front]) { printf("%c",q[front]->data); q[rear++]=q[front]->l; q[rear++]=q[front]->r; front++; } else front++; } } int main() { int t,len; char pre[101],in[101]; BinTree *root; root = (BinTree *)malloc(sizeof(BinTree)); scanf("%d",&t); getchar(); while(t--) { scanf("%s %s",pre,in); len = strlen(pre); root = creat(pre,in,len); postorder(root); printf("\n"); lorder(root); printf("\n"); } return 0; }
标签:des style blog io ar color os sp for
原文地址:http://www.cnblogs.com/6bing/p/4116488.html