编程语言:Java
题目:
题解:题目一共就两个条件:完全二叉树和二叉排序树。二叉排序树可以通过数组排序一步解决;完全二叉树就求根结点相对于两边的偏移即可,本人写的代码中是相对于左边界限进行偏移,其实也可以相对于右边界限进行偏移(当最后一层大于该层的一半时,就将大于的结点都加到右子树里去,反之就加0即可。)
结果:AC
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static Scanner sc = new Scanner(new BufferedInputStream(System.in));
static int[] a, res;
static int n;
public static void main(String[] args) throws IOException {
n = sc.nextInt();
a = new int[n];
res = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a);
BuildBST(0,0, a.length - 1);
for (int i = 0; i < n; i++)
if (i==0) {
out.print(res[i]);
} else
out.print(" " + res[i]);
out.flush();
}
private static void BuildBST(int root,int l, int r) {
int z = r - l + 1;
if (z == 0||root>=n)
return;
int m=getLeftLength(z);
res[root]=a[l+m];
BuildBST(2*root+1,l,l+m-1);
BuildBST(2*root+2,l+m+1,r);
}
private static int getLeftLength(int z) {
int i=1;
for(;i<100;i++){
int j= (int) (Math.pow(2,i)-1);
if(j>z)break;
}
int x= (int) (z-Math.pow(2,i-1)+1);
return (int) ((x>Math.pow(2,i-2)?Math.pow(2,i-2):x)+Math.pow(2,i-2)-1);
}
}