您的位置:首页 > 其它

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

2016-07-18 10:45 288 查看
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。

建立排序二叉树,判断是否是完全二叉树,判断方法,给排序二叉树编号(层次遍历的过程中给),如果存在编号大于n则不是完全二叉树。


输入格式:

输入第一行给出一个不超过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 <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
using namespace std;
struct node
{
int x;
int id;
node *l,*r;
};
int n;
int flag;
void build(node *&head,int x)
{
if(!head)
{
head=new node;
head->l=head->r=NULL;
head->x=x;
return ;
}
if(x>head->x)
build(head->l,x);
else
build(head->r,x);
}
void ceng(node *&head)
{
queue<node*>Q;
head->id=1;
Q.push(head);
node *tmp;
int first=1;
while(!Q.empty())
{
tmp=Q.front(),Q.pop();
if(tmp->id>n)
flag=1;
if(first)
first=0;
else
printf(" ");
printf("%d",tmp->x);
if(tmp->l)
Q.push(tmp->l),tmp->l->id=tmp->id<<1;
if(tmp->r)
Q.push(tmp->r), tmp->r->id=tmp->id<<1|1;
}
printf("\n");
}
int main()
{
node *head;
int x;
while(cin>>n)
{
head=NULL;
flag=0;
for(int i=0;i<n;i++)
{
scanf("%d",&x);
build(head,x);
}
ceng(head);
if(flag)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: