递归构建即可。
代码:
#include<iostream> #include<vector> #include<cmath> #include<algorithm> #include<fstream> using namespace std; vector<int>nodes; /** @parm l,r point for nodes @parm trees store constructed CBT @parm pos position for trees */ void buildCBT(int l,int r,const vector<int> &nodes ,vector<int> &trees,int pos){ if(l>r)return; if(l==r){ trees[pos] = nodes[l]; }else { int sumNode = r - l +1; int level = log((double)sumNode)/log((double)2) +1; int lastLevelNodes = pow((double)2,level-1); int knodes=lastLevelNodes-1;//除去最后一行的节点数 int lastRealNodes = sumNode -knodes; int offset =0; if(lastRealNodes>=lastLevelNodes/2){ offset = lastLevelNodes/2; }else{ offset = lastRealNodes; } int nodeIndex=l+knodes/2 +offset; //cout<<"nodeIndex "<<nodeIndex<<" "<<endl; trees[pos] = nodes[nodeIndex]; //cout<<"trees[pos] "<<trees[pos]<<" "; buildCBT(l,nodeIndex-1,nodes,trees,2*pos); buildCBT(nodeIndex+1,r,nodes,trees,2*pos+1); } } int main(){ ifstream cin("data.txt"); int num; cin>>num; int k; for(int i=0;i<num;++i){ cin>>k; nodes.push_back(k); } vector<int>trees(num+1); sort(nodes.begin(),nodes.end()); buildCBT(0,num-1,nodes,trees,1); for(int i=1;i<trees.size()-1;++i){ cout<<trees[i]<<" "; } cout<<trees[trees.size()-1]<<"\n"; //system("pause"); }
1064. Complete Binary Search Tree (30),布布扣,bubuko.com
1064. Complete Binary Search Tree (30)
原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/38678443