是否完全二叉搜索树 (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
判断一棵树是否是完全二叉树的思路 [3]
1>如果树为空,则直接返回错
2>如果树不为空:层序遍历二叉树
2.1>如果一个结点左右孩子都不为空,则pop该节点,将其左右孩子入队列;
2.1>如果遇到一个结点,左孩子为空,右孩子不为空,则该树一定不是完全二叉树;
2.2>如果遇到一个结点,左孩子不为空,右孩子为空;或者左右孩子都为空;则该节点之后的队列中的结点都为叶子节点;该树才是完全二叉树,否则就不是完全二叉树; [3]
#include<bits/stdc++.h>
#include<set>
#include<vector>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
};
//建二叉树
struct node *creat(int a,struct node *root)
{
if(root==NULL)
{
struct node *tail=new node;
tail->data=a;
tail->left=NULL;
tail->right=NULL;
root=tail;
}
else
{
if(a<root->data)
{
root->right=creat(a,root->right);
}
if(a>root->data)
{
root->left=creat(a,root->left);
}
}
return root;
};
//层序输出
int flag=1;
void cenxu(struct node *root)
{
struct node *temp[101];
int in=0,out=0;
temp[in++]=root;
while(in>out)
{
if(temp[out])
{
if(flag)
{
printf("%d",temp[out]->data);
flag=0;
}
else
printf(" %d",temp[out]->data);
temp[in++]=temp[out]->left;
temp[in++]=temp[out]->right;
}
out++;
}
}
//判断是否是完全二叉树
//树上的任意一个节点,与满二叉树一一对应的是完全二叉树
void judge(node *root,int n)
{
int cnt=0;
queue<node*>a;
a.push(root);
while(!a.empty())
{
struct node *frontt=a.front();
if(frontt->left!=NULL)
{
a.push(frontt->left);
}
else
{
a.push(frontt->left);
break;
}
if(frontt->right!=NULL)
{
a.push(frontt->right);
}
else
{
a.push(frontt->right);
break;
}
a.pop();
cnt++;
}
while(!a.empty())
{
a.pop();
cnt++;
}
cnt--;
if(cnt<n)
cout<<endl<<"NO";
else if(cnt==n)
cout<<endl<<"YES";
}
int main()
{
int n;
cin>>n;
int a[25];
for(int i=0;i<n;i++)
cin>>a[i];
struct node *root;
root=NULL;//必须初始化
for(int i=0;i<n;i++)
{
root=creat(a[i],root);
}
cenxu(root);
judge(root,n);
return 0;
}