//04-树6 Complete Binary Search Tree
import java.util.Scanner;
public class Main {
final int Max_Size = 1024;
static int Leftsubnum(int N){
int n = 0;
int sum = 0;
int i= 0;
int diceng = 0;
while(sum <= N){
sum += Math.pow(2, i++);
}
i --;
diceng = (int) (N - sum + Math.pow(2, i));
for(int j = 0; j <= i - 2; j ++){
n += Math.pow(2, j);
}
if(diceng < Math.pow(2, i - 1)){
n = n + diceng;
}
else{
n += Math.pow(2, i - 1);
}
return n;
}
static int[] sort(int[] a){
for(int i = 0; i < a.length; i ++) {
for (int j = 0; j < a.length - 1; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
}
}
}
return a;
}
static void solve(int left, int right, int root, int[] A, int[] T){
int n = right - left + 1;
if(n == 0){
return;
}
int L = Leftsubnum(n);
T[root] = A[left + L];
int leftroot = 2 * root + 1;
int rightroot = leftroot + 1;
solve(left, left + L - 1, leftroot, A, T);
solve(left + L + 1, right, rightroot, A, T);
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int N = s.nextInt();
int[] a = new int[N];
for(int i = 0; i < N; i ++){
a[i] = s.nextInt();
}
a = sort(a);
int[] T = new int[N];
solve(0, N - 1, 0, a, T);
for(int i = 0; i < N; i ++){
if(i < N - 1){
System.out.print(T[i] + " ");
}
else{
System.out.print(T[i]);
}
}
}
}
04-树6 Complete Binary Search Tree
最新推荐文章于 2024-05-29 15:37:18 发布