看了老师在慕课中的讲述,并参考博客04-树6 Complete Binary Search Tree (30分
结果最后不能有空格的控制:
for(i=0;i<N;++i){
if( i != 0 ) printf(" ");
printf("%d",output[i]);
}
C语言标准库函数的使用,不怎么会,有时间要看一看
int compare( const void* a, const void* b ){
return *(int*)a - *(int*)b;
}
qsort(input,N,sizeof(int),compare);
这部分计算总是写不对
int getLeftLength(int n){
//利用二叉树的性质:满二叉树第i层有 2^(i-1) 个结点, 高为h的满二叉树有 2^h - 1 个结点(从1开始)
double h, x, L, t;
h = (double)(int)( log((double)n+1) / log(2.0) );
//h = floor( log((double)n+1) / log(2.0) );
x = n - pow(2.0, h) + 1 ;
t = pow(2.0, h - 1.0);
x = x < t ? x : t;
L = t - 1 + x;
return (int)L;
}
自己写的
int findr(int n){
double h,x,n1;
n1 = (double)n;//success
h = (log2(n1))+1;//success
h = floor(h);//转化为int之后变成0
printf("%f\n",h);
x = (n-(pow(2,h-1)-1))>pow(2,h-2)? pow(2,h-2):(n-(pow(2,h-1)-1));
return (int)((pow(2,h-2)-1)+x);
}
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAXSIZE 1005
int input[MAXSIZE],output[MAXSIZE];
int compare( const void* a, const void* b ){
return *(int*)a - *(int*)b;
}
int getLeftLength(int n){
//利用二叉树的性质:满二叉树第i层有 2^(i-1) 个结点, 高为h的满二叉树有 2^h - 1 个结点(从1开始)
double h, x, L, t;
h = (double)(int)( log((double)n+1) / log(2.0) );
//h = floor( log((double)n+1) / log(2.0) );
x = n - pow(2.0, h) + 1 ;
t = pow(2.0, h - 1.0);
x = x < t ? x : t;
L = t - 1 + x;
return (int)L;
}
void sovle(int left,int right,int root){
int n,r,leftroot,rightroot;
n = right-left+1;
if(n==0) return;
r = getLeftLength(n);
output[root] = input[left+r];
leftroot = 2*root + 1;
rightroot = 2*root + 2;
sovle(left,left+r-1,leftroot);
sovle(left+r+1,right,rightroot);
}
int main(){
int i,N,v;
scanf("%d",&N);
for(i=0;i<N;++i){
scanf("%d",&v);
input[i] = v;
}
qsort(input,N,sizeof(int),compare);
sovle(0,N-1,0);
for(i=0;i<N;++i){
if( i != 0 ) printf(" ");
printf("%d",output[i]);
}
return 0;
}