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
很有意思的题目。学到了一种新的二叉搜索树的构造方法。即递归构造,要注意递归构造的时候,由于要通过形参修改实参的实际值,而实参是指针,所以这边形参要设置为指针的指针。void Insert(Btree *&r,int x)。注意这边的&
完全二叉树的判断可以通过编号来实现,完全二叉树中,按理说左子树编号=当前节点编号*2,右子树编号=当前节点编号*2+1。在层次遍历的时候,对节点进行编号,如果发现存在编号值>n的情况,就不是完全二叉树。
思路来源 http://blog.youkuaiyun.com/lv414333532/article/details/51939986
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <cmath>
#define INF 1000000
using namespace std;
struct Btree
{
int x;
int id;
Btree *left;
Btree *right;
Btree(int aa)
{
x=aa;
left=right=NULL;
id=0;
}
};
typedef struct Btree Btree;
int n;
int a[50];
Btree *root=NULL;
void Insert(Btree *&r,int x)
{
if(r==NULL)
{
r=new Btree(x);
return ;
}
else
{
if(x>r->x)
{
Insert(r->left,x);
}
else
{
Insert(r->right,x);
}
}
}
int flag=0;
int ans[100];
void CenOrder()
{
queue<Btree*> Q;
root->id=1;
Q.push(root);
int j=0;
while(Q.size()>0)
{
Btree *tmp=Q.front();
Q.pop();
ans[j++]=tmp->x;
if(tmp->id>n)
{
flag=1;
}
if(tmp->left)
{
tmp->left->id=tmp->id*2;
Q.push(tmp->left);
}
if(tmp->right)
{
tmp->right->id=tmp->id*2+1;
Q.push(tmp->right);
}
}
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(int i=0;i<n;i++)
{
Insert(root,a[i]);
}
CenOrder();
for(int i=0;i<n;i++)
{
if(i==0) printf("%d",ans[i]);
else printf(" %d",ans[i]);
}
printf("\n");
if(flag==1)
{
printf("NO\n");
}
else
{
printf("YES\n");
}
return 0;
}