//这道题目的关键是每一次处理都要找出根节点
#include<iostream>
#include<fstream>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<math.h>
#include<string>
#include <iomanip> //要用到格式控制符
using namespace std;
int *data=NULL;
int N;
int num=0;
int c;
int th;
struct node
{
int value;
node *left,*right;
node(){value=0;left=right=NULL;}
};
node *man(int begin,int end)
{
if(begin>end)
return NULL;
if(begin==end)
{
node *temp=new node;
temp->value=data[begin];
return temp;
}
else
{
num=end-begin+1;
c=1;
while(int(pow(2.0,c))-1<num)
{
c++;
}
th=0;
if(c>=2)
{
if((num-pow(2.0,c-1)+1)<=(pow(2.0,c)-pow(2.0,c-1))/2)
th=pow(2.0,c-2)-1+num-pow(2.0,c-1)+1+begin;
else
th=pow(2.0,c-2)-1+(pow(2.0,c)-pow(2.0,c-1))/2+begin;
int itemp=th;
node *temp=new node;
temp->value=data[th];
temp->left=man(begin,th-1);
th=itemp;
temp->right=man(th+1,end);
th=itemp;
return temp;
}
else
{
if(num==3)
{
node *temp=new node;
temp->value=data[begin+1];
temp->left=man(begin,begin);
temp->right=man(end,end);
return temp;
}
else
{
node *temp=new node;
temp->value=data[begin+1];
temp->left=man(begin,begin);
return temp;
}
}
}
}
void levelprint(node *tree)
{
queue<node*> my;
if(tree)
{
if(tree->left)
my.push(tree->left);
if(tree->right)
my.push(tree->right);
cout<<tree->value;
}
while(my.size())
{
cout<<" "<<my.front()->value;
if(my.front()->left)
{
my.push(my.front()->left);
}
if(my.front()->right)
{
my.push(my.front()->right);
}
my.pop();
}
}
//#define fin cin
int main()
{
/*ifstream fin("d:\in.txt" );
if (! fin.is_open())
{
cout << "Error opening file";
system("pause");
exit (1);
}*/
cin>>N;
data=new int[N];
for(int i=0;i<N;i++)
{
cin>>data[i];
}
sort(data,data+N);
//node *man(int begin,int end)
node *root=NULL;
root=man(0,N-1);
levelprint(root);
system("PAUSE");
return 0;
}