-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path完全二叉搜索树.cpp
57 lines (47 loc) · 1.01 KB
/
完全二叉搜索树.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int b[1005];
int j=0;
int compare(const void * a, const void * b)
{
return *(int *)a - *(int *)b;
}
int min(double a, double b)
{
if(a <b) return a;
else return b;
}
void BST(int left, int right, int root,int a[])
{
int flag,h,resume,temp;
int leftroot, rightroot;
flag = right - left +1;
if (!flag)
return;
h = log(flag + 1)/log(2);
resume = min(flag +1 - pow(2,h),pow(2,h-1));
temp = pow(2,h-1) -1 + resume;
b[root] = a[temp+left];
leftroot = root*2 +1;
rightroot = leftroot +1;
//recursion
BST(left, left+temp-1, leftroot, a);
BST(left+temp+1, right, rightroot, a);
}
int main(){
int N;
int i=0;
scanf("%d",&N);
int a[N];
for(i=0;i<N;i++){
scanf("%d",&a[i]);
}
qsort(a,N,sizeof(int),compare);
BST(0, N-1,0,a);
printf("%d",b[0]);
for(i=1;i<N;i++){
printf(" %d",b[i]);
}
return 0;
}