浙大PAT1064

//这道题目的关键是每一次处理都要找出根节点

#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;  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值