将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过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 <bits/stdc++.h>
using namespace std;
struct Tree
{
int Ele;
struct Tree *Left;
struct Tree *Right;
};
typedef struct Tree* T;
int n;
T Insert(T root,int key);
void Layer(T root); //层序遍历
int whether=1; //是不是完全二叉树
int main()
{
cin>>n;
int key;
T root=NULL;
for (int i=0;i<n;i++)
{
cin>>key;
root=Insert(root,key);
}
Layer(root);
cout<<endl;
if (whether==0)
{
cout<<"NO";
}
else
{
cout<<"YES";
}
return 0;
}
T Insert(T root,int key) //9 38 45 42 24 58 30 67 12 51
{
if (root==NULL)
{
root=(T)malloc(sizeof(struct Tree));
root->Ele=key;
root->Left=root->Right=NULL;
return root;
}
T now;
if (key>root->Ele)
{
now=Insert(root->Left,key);
root->Left=now;
}
else if (key<root->Ele)
{
now=Insert(root->Right,key);
root->Right=now;
}
return root;
}
void Layer(T root)
{
if (root==NULL) //空树
{
whether=0;
return;
}
int flag=0,partflag=0; //partflag记录是否已经遇到了完全二叉树的最后一个有孩子的节点
queue<T>q;
q.push(root);
while (!q.empty())
{
T x;
x=q.front();
q.pop();
if (partflag==1&&(x->Left!=0||x->Right!=0))
{
whether=0;
}
if (x->Left==NULL&&x->Right!=NULL) //没有左孩子有右孩子,这不是二叉树
{
whether=0;
}
if (x->Left==NULL&&x->Right==NULL||x->Left!=NULL&&x->Right==NULL) //遇到了内个节点
{
partflag=1;
}
(flag==0)?printf("%d",x->Ele),flag=1:printf(" %d",x->Ele);
if (x->Left!=NULL)
q.push(x->Left);
if (x->Right!=NULL)
q.push(x->Right);
}
return;
}