1064 Complete Binary Search Tree
作者:互联网
正向思维硬解得分28,最初不知道中序遍历如何解,测试点3不思考为啥错误了
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 1010;
int orinOrder[maxn],N;
vector<int> orderCBT,levelOrder;
struct node
{
int data;
node *lchild, *rchild;
};
node* newNode(int dataX)
{
node* root = new node;
root->data = dataX;
root->lchild = root->rchild = NULL;
return root;
}
void insert(node* &root,int dataX)
{
if(root == NULL)
{
root = newNode(dataX);
return;
}
if(root->data == dataX) return;
else if(root->data > dataX) insert(root->lchild,dataX);
else insert(root->rchild,dataX);
}
node* create()
{
node* root = newNode(orderCBT[0]);
for(int i = 0; i < N; i++)
{
insert(root,orderCBT[i]);
}
return root;
}
void createCBT(int L,int R)
{
if(L > R) return;
int len;
if(L != 0 and R != N) len = R - L + 1;
else len = R - L;
double tempExp = log(double(len) + 1.0) / log(2.0);
int exp = tempExp;
int rest = len - (int)pow(2.0,exp) + 1;
int addition;
if(rest <= 0)
{
addition = (int)pow(2.0,exp - 1) - 1;
if(addition < 0) addition = 0;
}
else if(rest >= (int)pow(2.0,exp - 1))
{
addition = (int)pow(2.0,exp) - 1;
}
else addition = (int)pow(2.0,exp - 1) - 1 + rest;
int pos = L + addition;
orderCBT.push_back(orinOrder[pos]);
createCBT(L,pos - 1);
createCBT(pos + 1,R);
}
void BFS(node* root)
{
queue<node*> q;
q.push(root);
node* tempRoot;
while(!q.empty())
{
tempRoot = q.front();
q.pop();
levelOrder.push_back(tempRoot->data);
if(tempRoot->lchild != NULL) q.push(tempRoot->lchild);
if(tempRoot->rchild != NULL) q.push(tempRoot->rchild);
delete(tempRoot);
}
for(int i = 0; i < N; i++)
{
if(i == 0) printf("%d",levelOrder[i]);
else printf(" %d",levelOrder[i]);
}
}
int main()
{
scanf("%d",&N);
for(int i = 0; i < N; i++)
{
scanf("%d",&orinOrder[i]);
}
sort(orinOrder,orinOrder+N);
createCBT(0,N);
node* root = create();
BFS(root);
}
标签:node,Binary,Search,orinOrder,int,Tree,dataX,root,tempRoot 来源: https://blog.csdn.net/weixin_45965599/article/details/122761168