Data Structures and Algorithms (English) 7-7 Complete Binary Search Tree #include <stdio.h> #include <stdlib.h> #include <math.h> #define Max 1000 int A[Max]; int T[Max]; int comp(const void*a, const void*b)//用来做比较的函数。 { return *(int*)a - *(int*)b; } /* *@program 获得左子树的规模(利用完全二叉树的特性) *@param n 母树的规模 */ int getALeftLength(int n) { int depth = floor(log(n+1) / log(2));//母树的深度 int x = n + 1 - pow(2, depth); x = (x < pow(2, depth - 1)) ? x : pow(2, depth - 1); return x + pow(2, depth-1)-1; } /* *@program 核心算法 *@param ALeft 当前树最左端的下标 *@param ARight 当前树最右端的下标 *@param TRoot 树T根节点的下标 */ void solve(int ALeft, int ARight, int TRoot) { int n = ARight - ALeft + 1;//为当前树的规模 if (n == 0) return; int leftLength = getALeftLength(n); T[TRoot] = A[ALeft + leftLength]; int TLeftRoot = TRoot * 2 + 1; int TRightRoot = TLeftRoot + 1; solve(ALeft, ALeft + leftLength - 1, TLeftRoot); solve(ALeft + leftLength + 1, ARight, TRightRoot); } int main() { int n, number; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &number); A[i] = number; } qsort(A, n, sizeof(int), comp); solve(0, n - 1, 0); for (int i = 0; i < n; i++) { printf("%d", T[i]); if (i != n - 1) { printf(" "); } } }