1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| #include<stdio.h> #include<Windows.h>
typedef char ElemType; typedef struct Node{ ElemType elem; struct Node *LChild; struct Node *RChild; }BiTNode, *BiTree;
void ReBuildByPreAndInOrder(char *prelist, char *inlist, int len, BiTree *bt){ if(!prelist || !inlist || len<=0 ) return; int i; for(i = 0; i < len; i++){ if(inlist[i] == prelist[0]) break; } if(i>=len) return; *bt = (BiTNode*)malloc(sizeof(BiTNode)); if(!bt) return; (*bt)->LChild = (*bt)->RChild = NULL; (*bt)->elem = prelist[0]; ReBuildByPreAndInOrder(prelist+1, inlist, i, &(*bt)->LChild); ReBuildByPreAndInOrder(prelist+i+1, inlist+i+1, len-i-1, &(*bt)->RChild); }
void ReBuildByInAndPostOrder(char *inlist,char *postlist, int len, BiTree *bt){ if(!inlist || !postlist || len<=0 ) return; int i; for(i = 0; i < len; i++){ if(inlist[i] == postlist[len-1]) break; } if(i>=len) return; *bt = (BiTNode*)malloc(sizeof(BiTNode)); if(!bt) return; (*bt)->LChild = (*bt)->RChild = NULL; (*bt)->elem = postlist[len-1]; ReBuildByInAndPostOrder(inlist, postlist, i, &(*bt)->LChild); ReBuildByInAndPostOrder(inlist+i+1, postlist+i, len-i-1, &(*bt)->RChild); }
void PrintTree(BiTree bt,int nLayer){ int i; if(bt==NULL) return; PrintTree(bt->RChild,nLayer+1); for(i=0;i<nLayer;i++) printf(" "); printf("%c\n", bt->elem); PrintTree(bt->LChild,nLayer+1); }
void main(){ char pre[7]={'A', 'B', 'D', 'E', 'C', 'F', 'G'}, inorder1[7] = {'D', 'B', 'E', 'A', 'F', 'C', 'G'}, inorder2[9] = {'G', 'D', 'H', 'B', 'A', 'E', 'C', 'I', 'F'}, post[9] = {'G', 'H', 'D', 'B', 'E', 'I', 'F', 'C', 'A'}; int i=0;
printf("Give the preorder and midorder traversal of a binary tree: \nPreorder = "); for(i=0; i<7; i++){ printf("%c ", pre[i]); } printf("\nMidorder = "); for(i=0; i<7; i++){ printf("%c ", inorder1[i]); }
BiTree T1=NULL; ReBuildByPreAndInOrder(pre, inorder1, 7, &T1); printf("\nThe binary tree constructed by two traversal sequences is: \n"); PrintTree(T1, 1);
printf("Give the midorder and postorder traversal of a binary tree: \nMidorder = "); for(i=0; i<9; i++){ printf("%c ", inorder2[i]); } printf("\nPostorder = "); for(i=0; i<9; i++){ printf("%c ", post[i]); }
BiTree T2=NULL; ReBuildByInAndPostOrder(inorder2, post, 9, &T2); printf("\nThe binary tree constructed by two traversal sequences is: \n"); PrintTree(T2, 1);
system("pause"); }
|