您的位置:首页 > 其它

1064.Complete Binary Search Tree

2015-01-22 18:50 183 查看
【题意】
给出一个BST的所有元素,要求这个BST同时是完全二叉树,输出这个二叉树的层先遍历序列

【思路】
对于一个完全二叉树,总的节点数给出后左右子树的节点数就确定了,再结合BST的中序遍历是递增数列的特性,就可以递归地建树了。层先遍历自然是借助队列实现

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;

vector<int> numbers;

typedef struct node{
int value;
node *left;
node *right;
}BiNode;

void nodeCnt(int n, int *leftCnt, int *rightCnt){
int h;

h = (int)(log(n*1.0)/log(2.0))+1;
if(h==1){
*leftCnt = *rightCnt = 0;
}
else{
if(3*pow(2.0,h-2)-1>=n){
*rightCnt = pow(2.0,h-2)-1;
*leftCnt = n-1-*rightCnt;
}
else{
*leftCnt = pow(2.0,h-1)-1;
*rightCnt = n-1-*leftCnt;
}
}
}

BiNode *buildTree(int leftIndex, int rightIndex){
int n,leftCnt,rightCnt;
BiNode *father;

n = rightIndex-leftIndex+1;
father = (BiNode*)malloc(sizeof(BiNode));
nodeCnt(n,&leftCnt,&rightCnt);
father->value = numbers[leftIndex+leftCnt];
if(leftCnt==0){
father->left = NULL;
}
else{
father->left = buildTree(leftIndex,leftIndex+leftCnt-1);
}
if(rightCnt==0){
father->right = NULL;
}
else{
father->right = buildTree(rightIndex-rightCnt+1,rightIndex);
}
return father;
}

int main(int argc, char const *argv[])
{
int n;

cin >> n;
numbers.resize(n);
for(int i=0; i<n; i++){
cin >> numbers[i];
}
sort(numbers.begin(),numbers.end());

BiNode *head = buildTree(0,n-1);

bool first = true;
queue<BiNode*> qq;
qq.push(head);
while(!qq.empty()){
if(first){
first = false;
}
else{
cout << " ";
}
cout << qq.front()->value;
if(qq.front()->left!=NULL){
qq.push(qq.front()->left);
}
if(qq.front()->right!=NULL){
qq.push(qq.front()->right);
}
qq.pop();
}

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: