您的位置:首页 > 其它

L3-010. 是否完全二叉搜索树

2018-03-14 10:05 453 查看

L3-010. 是否完全二叉搜索树

时间限制400 ms
内存限制65536 kB
代码长度限制8000 B
判题程序Standard作者陈越
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。输入格式:输入第一行给出一个不超过20的正整数N;第二行给出N个互不相同的正整数,其间以空格分隔。输出格式:将输入的N个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出“YES”,如果该树是完全二叉树;否则输出“NO”。输入样例1:
9
38 45 42 24 58 30 67 12 51
输出样例1:
38 45 24 58 42 30 12 67 51
YES
输入样例2:
8
38 24 12 45 58 67 42 51
输出样例2:
38 45 24 58 42 12 67 51
NO
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
using namespace std;
struct node{
int val;
int ced;
node* left;
node* right;
};
node * root;
int n;
node* build(node* rt,int num ){
if(rt==NULL)
{
rt=new node;
rt->val=num;
rt->left=NULL;
rt->right=NULL;
return rt;
}
if(rt->val<num){
rt->left=build(rt->left,num );
}
else rt->right=build(rt->right,num );
return rt;
}
void level(){
bool ans=true;
vector<int> vec;
queue<node*> rt;
root->ced=1;
rt.push(root);
bool over=false;
while(!rt.empty()){
node *tmp=rt.front();
rt.pop();
vec.push_back(tmp->val);
if(tmp->ced  >  n)
ans=false;
if(tmp->left){
rt.push(tmp->left);
tmp->left->ced=tmp->ced*2;
}
if(tmp->right){
rt.push(tmp->right);
tmp->right->ced=tmp->ced*2+1;
}
}
for(int i=0;i<vec.size();i++)
{
if(i!=0)
cout<<" ";
cout<<vec[i];
}

int k=1,nu=0;
cout<<endl;
if(ans)
cout<<"YES"<<endl;
else cout<<"NO"<<endl;
return ;
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
int num;
cin>>num;
root=build(root,num);
}
level();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: