数据结构1 04-树6 Complete Binary Search Tree
1 #include<stdio.h> 2 #define MAXN 1001 3 int n,a[MAXN],b[MAXN],c[10]; 4 void read(); 5 void sort(); 6 void cbt(int len,int pos,int start); 7 int main(){ 8 c[0] = 1; 9 for(int i=1;i<=9;i++) c[i] = c[i-1]*2; 10 read(); 11 cbt(n,1,1); 12 for(int i=1;i<=n;i++){ 13 printf("%d",b[i]); 14 if(i!=n) printf(" "); 15 } 16 return 0; 17 } 18 void read(){ 19 int i; 20 scanf("%d",&n); 21 for(i=1;i<=n;i++) scanf("%d",&a[i]); 22 sort(); 23 } 24 void sort(){ 25 int i,j,temp,value; 26 for(i=1;i<=n;i++){ 27 temp = i; 28 for(j=i+1;j<=n;j++){ 29 if(a[temp]>a[j]) temp = j; 30 } 31 value = a[i]; 32 a[i] = a[temp]; 33 a[temp] = value; 34 } 35 } 36 void cbt(int len,int pos,int start){ 37 if(len==1) { 38 b[pos] = a[start]; 39 return; 40 } 41 else if(len==0){ //1忽略的问题 42 return; 43 } 44 else{ 45 int llen,rlen,i,len2; 46 len2 = len-1; 47 llen = 0; 48 rlen = 0; 49 for(i=1;i<=9;i++){ 50 if(len2 > c[i]){ 51 len2 = len2-c[i]; 52 llen += c[i]/2; 53 rlen += c[i]/2; 54 } 55 else if(len2 == c[i]){ 56 len2 = len2 - c[i]; 57 llen += c[i]/2; 58 rlen += c[i]/2; 59 break; 60 } 61 else if(len2 < c[i]){ 62 //此为最后一层 63 if(len2<=c[i]/2){ 64 llen += len2; 65 66 }else{ 67 llen += c[i]/2; 68 len2 = len2 - c[i]/2; 69 rlen += len2; 70 } 71 break; 72 } 73 } 74 b[pos] = a[start+llen]; //2粗心的问题 75 cbt(llen,pos*2,start); 76 cbt(rlen,pos*2+1,start+llen+1); 77 78 } 79 80 81 82 }