L3-010 是否完全二叉搜索树 (30 分)
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
复习满二叉树和完全二叉树就贴一篇dalao的博客吧
#include<bits/stdc++.h>
using namespace std;
const int N=2e6+7;
map<int,int>tree;
//int tree[N];
int n,x;
int mmax=0;
void creat(int id,int x){
if(!tree[id]){
tree[id]=x;
mmax=max(id,mmax);
return ;
}
else if(x<tree[id]) creat(id*2+1,x);//题目定义二叉搜索树的性质,大于根节点放在根节点左边 2*id+1
else creat(id*2,x);//题目定义小于根节点放在根节点右边 2*id
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>x;
creat(1,x);
}
//cout<<tree.size()<<endl;
queue<int>q;
q.push(1);
int pe=0;
while(q.size()){
auto it=q.front();q.pop();
if(tree[it*2]) q.push(it*2);
if(tree[it*2+1]) q.push(it*2+1);
if(!pe) cout<<tree[it];
else cout<<" "<<tree[it];
pe++;
}
puts("");
if(mmax==n) puts("YES");
else puts("NO");
return 0;
}