1064 Complete Binary Search Tree
题目地址
完全二叉树和二叉搜索树结合
聪明办法:
#include <stdio.h>
#include <string.h>
#include <vector>
#include <math.h>
#include <algorithm>
#include <queue>
using namespace std;
//int arr[1000];
int N;
vector<int> arr;
vector<int> res;
int index=1;
struct node{
int data;
node* left;
node* right;
// int layer;
};
bool cmp(int a,int b){
return a<b;
}
void inorder(int root){
if(root>N) return;
inorder(2*root);
res[root]=arr[index++];
inorder(2*root+1);
return;
}
int main(){
scanf("%d",&N);
arr.resize(N+1);
res.resize(N+1);
for(int i=1;i<=N;i++){
scanf("%d",&arr[i]);
}
sort(arr.begin(),arr.end(),cmp);
inorder(1);
for(int i=1;i<=N;i++){
printf("%d",res[i]);
if(i!=N) printf(" ");
}
return 0;
}
笨办法
(还没能ac,有两个用例没找到错误原因)
通过计算左右子树的个数来确定根节点在中序中的序号
代码:
#include <stdio.h>
#include <string.h>
#include <vector>
#include <math.h>
#include <algorithm>
#include <queue>
#define MAX 100000
//freopen("1.txt","r",stdin);
using namespace std;
int arr[1000];
struct node{
int data;
node* left;
node* right;
// int layer;
};
bool cmp(int a,int b){
return a<b;
}
void layerorder(node *root){
queue<node*> q;
q.push(root);
int first=1;
while(!q.empty()){
node *now=q.front();
if(first){
printf("%d",now->data);
first=0;
}
else{
printf(" %d",now->data);
}
q.pop();
if(now->left!=NULL) q.push(now->left);
if(now->right!=NULL) q.push(now->right);
}
}
node* create(int lefti,int righti){
if(lefti>righti) return NULL;
int nodeindex;
int leftnum;
int rightnum;
int len=righti-lefti;
int i=0;
if(len==0){
node *root=new node;
root->data=arr[lefti];
root->left=create(1,0);
root->right=create(1,0);
return root;
}
if(len==1){
node *root=new node;
root->data=arr[righti];
root->left=create(lefti,lefti);
root->right=create(1,0);
return root;
}
while(len>=pow(2,++i)){}
leftnum=rightnum=pow(2,i-2)-1;
leftnum+=(len-leftnum-rightnum)>=i?i-1:(len-leftnum-rightnum);
rightnum=len-leftnum;
nodeindex=leftnum+lefti;
node* root=new node;
root->data=arr[nodeindex];
root->left=create(nodeindex-leftnum,nodeindex-1);//create(0,5)
root->right=create(nodeindex+1,nodeindex+rightnum);//create(7,10)
return root;
}
int main(){
freopen("1.txt","r",stdin);
int N;
scanf("%d",&N);
for(int i=0;i<N;i++){
scanf("%d",&arr[i]);
}
sort(arr,arr+N,cmp);
int nodeindex;
int leftnum;
int rightnum;
int len=N;
int i;
layerorder(create(0,N-1));
return 0;
}