提交格式:实现void solve(int n, int *preOrder, int *inOrder, int *outOrder)函数。
函数参数为序列长度n、先序序列preOrder、中序序列inOrder和输出序列outOrder。1<=n<=1000000,树的深度<=2000。请不要printf输出任何内容。
intmain() { int N; scanf_s("%d", &N); int* pre = (int*)malloc(N * sizeof(int)); if (pre == NULL) return0; int* in = (int*)malloc(N * sizeof(int)); if (in == NULL) return0; int* out = (int*)malloc(N * sizeof(int)); if (out == NULL) return0; for (int i = 0; i < N; i++) { scanf_s("%d", &pre[i]); } for (int j = 0; j < N; j++) { scanf_s("%d", &in[j]); } solve(N, pre, in, out); printf("\n"); return0; }
solve函数
1 2 3 4 5 6 7 8 9 10 11 12 13
voidsolve(int n, int* preOrder, int* inOrder, int* outOrder) { PBiTNode root=NULL; if (n <= 0 || preOrder==NULL|| inOrder==NULL|| outOrder==NULL) { return; } else { CreatepostBiTree(preOrder, inOrder, 0, n - 1, 0, n - 1, root); PreOrder(root, outOrder); } }
CreatepostBiTree函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
voidCreatepostBiTree(int preord[], int inord[], int i, int j, int k, int h, PBiTNode &t) { /* 先序序列中从i到j,中序序列从k到h,建立一棵二叉树放在t中*/ int m; t = (BiTNode*)malloc(sizeof(BiTNode)); if (t == NULL) return ; t->data = preord[i]; /*二叉树的根*/ m = k; while (inord[m] != preord[i]) m++; /*在中序序列中定位树的根*/ /*递归调用建立左子树*/ if (m == k) t->lchild = NULL; /*左子树空*/ else CreatepostBiTree(preord, inord, i + 1, i + m - k, k, m - 1, (t->lchild)); /*递归调用建立右子树*/ if (m == h) t->rchild = NULL; /*右子树空*/ else CreatepostBiTree(preord, inord, i + m - k + 1, j, m + 1, h, (t->rchild)); }