由前序遍历串与中序遍历串还原二叉树,并得到二叉树的后序遍历串。
1 #include<stdio.h> 2 #include<string.h> 3 struct Node{ //树结点结构体 4 Node *lchild; 5 Node *rchild; 6 char c; 7 }Tree[50]; 8 9 int loc;//静态数组中已经分配的结点个数 10 Node *creat(){//申请一个结点空间,返回指向其的指针 11 Tree[loc].lchild = Tree[loc].rchild = NULL; 12 return &Tree[loc++]; 13 } 14 15 void postOrder(Node * T){//后序遍历树 16 if(T->lchild != NULL) 17 postOrder(T->lchild ); 18 if(T->rchild != NULL) 19 postOrder(T->rchild ); 20 printf("%c",T->c ); 21 } 22 23 char str1[30],str2[30]; 24 Node *build(int s1,int e1,int s2,int e2)//由前序和中序遍历结果还原二叉树 25 { 26 Node *root = creat(); 27 root->c = str1[s1]; 28 int rootidx; 29 for(int i=s2;i<=e2;i++) 30 { 31 if(str1[s1]==str2[i]) 32 { 33 rootidx = i; 34 break; 35 } 36 } 37 38 if(rootidx!=s2)//左子树不为空 39 { 40 root->lchild = build(s1+1,s1+(rootidx-s2),s2,rootidx-1); 41 } 42 if(rootidx!=e2)//右子树不为空 43 { 44 root->rchild = build(s1+(rootidx-s2)+1,e1,rootidx+1,e2); 45 } 46 return root; 47 } 48 49 int main() 50 { 51 while(scanf("%s",str1)!=EOF) 52 { 53 // getchar(); 54 scanf("%s",str2); 55 loc = 0; 56 int l1 = strlen(str1); 57 int l2 = strlen(str2); 58 Node *T = build(0,l1-1,0,l2-1); 59 postOrder(T); 60 printf(" "); 61 } 62 return 0; 63 }