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
| #include<stdio.h> #include<string.h> #include<stdlib.h>
struct BiTree { char val; struct BiTree* lchild; struct BiTree* rchild; };
char* slice(const char arr[], int a, int b) { char* res = malloc(b - a + 1); int i; for (i = 0; i < b - a; i++) { res[i] = arr[i + a]; } res[i] = '\0'; return res; }
struct BiTree* buildTree(char pre[], char in[], int size) { if (size <= 0) { return NULL; } struct BiTree* root = malloc(sizeof(struct BiTree)); root->val = pre[0]; int rootPos; for (rootPos = 0; rootPos < size; rootPos++) { if (in[rootPos] == pre[0]) break; } char* leftPre = slice(pre, 1, rootPos + 1); char* leftIn = slice(in, 0, rootPos); char* rightPre = slice(pre, rootPos + 1, size); char* rightIn = slice(in, rootPos + 1, size);
root->lchild = buildTree(leftPre, leftIn, rootPos); root->rchild = buildTree(rightPre, rightIn, size - rootPos - 1);
free(leftPre); free(leftIn); free(rightPre); free(rightIn);
return root; }
void posTrav(struct BiTree* root) { if (root != NULL) { posTrav(root->lchild); posTrav(root->rchild); printf("%c", root->val); free(root); } }
int main() { while(1) { char pre[50]; char in[50]; scanf("%s", pre); scanf("%s", in);
int size = strlen(pre); struct BiTree* tree = buildTree(pre, in, size);
posTrav(tree); printf("\n"); } return 0; }
|