MOOC Zhejiang University Data Structure-04-Tree 6 Árbol de búsqueda binario completo (30 puntos)

Lea la descripción del profesor en el MOOC y consulte el blog 04- 树 6 Árbol de búsqueda binario completo (30 puntos

Como resultado, no puede haber control de espacio al final:

    for(i=0;i<N;++i){
    
    
        if( i != 0 ) printf(" ");
        printf("%d",output[i]);
    }

El uso de las funciones de la biblioteca estándar del lenguaje C no es muy bueno, tenga tiempo para echar un vistazo

int compare( const void* a, const void* b ){
    
    
	return *(int*)a - *(int*)b;
}
qsort(input,N,sizeof(int),compare);

Esta parte del cálculo siempre es incorrecta

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;
}

Escrito por mi mismo

 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;
}

Supongo que te gusta

Origin blog.csdn.net/weixin_43919570/article/details/105202344
Recomendado
Clasificación