L3-010 是否完全二叉搜索树 (30 分)
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过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
完全二叉树的编号和满二叉树相同,所以可以给每个结点都编号,如果超过了20或者在1-最大值中有一个不存在就证明不是完全二叉树。
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<string>
#include<sstream>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
#define inf 0x3f3f3f3f
#define LL long long
struct Node
{
int val;
struct Node *l,*r;
Node():val(-1),l(NULL),r(NULL){
};
};
struct Node* newnode(){
return new struct Node();
}
struct Node* root=newnode();
void insert(struct Node* root,int x)
{//建树
if(root->val==-1) root->val=x;
else
{
if(x>=root->val)
{
if(!root->l) root->l=newnode();
insert(root->l,x);
}
else
{
if(!root->r) root->r=newnode();
insert(root->r,x);
}
}
}
vector<int> c;
queue<struct Node*> q;
void cc(struct Node* root)
{
q.push(root);
while(!q.empty())
{
struct Node* u=q.front();
c.push_back(u->val);
q.pop();
if(u->l)q.push(u->l);
if(u->r)q.push(u->r);
}
}
int has[25],maxx;
void check(struct Node* u,int id)
{
if(u==NULL)return;
maxx=max(maxx,id);
if(id<=20)has[id]=1;
check(u->l,id*2);
check(u->r,id*2+1);
}
int main()
{
int n,i,j,a[1005];
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
insert(root,a[i]);
}
cc(root);
check(root,1);
for(int i=0;i<c.size();i++)
printf("%d%c",c[i],(int)c.size()-1==i?'\n':' ');
if(maxx>20)printf("NO\n");
else
{
int f=1;
for(int i=1;i<=maxx;i++)if(!has[i])f=0;
if(f)printf("YES\n");
else printf("NO\n");
}
}