题意
求一个完全二叉树的二叉排序树
解题思路
对于完全二叉树我们可以先求出左子树的大小A和右子树的大小B,又由于二叉排序树根节点的值应大于左子树的所有节点,小于右子树的所有节点,所以根节点的值应该是升序数组中的第A+1个数,同理可对左子树和右子树同样进行递归求解。
参考代码
#include <bits/stdc++.h>
using namespace std;
int n;
int a[1000+5];
typedef struct Node{
struct Node *l,*r;
int v;
}*tree;
void build(tree &t,int x,int num){
if (num==0) return;
int y=num;
int k=1;
for (int i=1;;i++){
if (y<k) break;
y-=k;
k*=2;
}
int l=0,r=0;
if (y>k/2){
l=(num-y)/2+k/2;
r=(num-y)/2+y-k/2;
}
else{
l=(num-y)/2+y;
r=(num-y)/2;
}
if (t==NULL){
t=new Node;
t->v=x+l+1;
t->l=t->r=NULL;
}
build(t->l,x,l);
build(t->r,x+l+1,r);
}
void LevelOrder(tree t){
queue<tree> que;
que.push(t);
int flag=0;
while (!que.empty()){
tree temp=que.front();
if (temp->l) que.push(temp->l);
if (temp->r) que.push(temp->r);
if (flag)
cout<<" "<<a[temp->v-1];
else{
cout<<a[temp->v-1];
flag=1;
}
que.pop();
}
cout<<endl;
}
int main(){
while (cin>>n){
for (int i=0;i<n;i++) cin>>a[i];
sort(a,a+n);
tree t=NULL;
build(t,0,n);
LevelOrder(t);
}
return 0;
}