版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_42623428/article/details/84379689
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过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;
bool f=true,exs=false;
typedef struct BNode *BinTree;
struct BNode
{
int data;
BinTree left;
BinTree right;
};
void Insert(BinTree &t,int e){
if(!t){
t=(BinTree)malloc(sizeof(BNode));
t->left=t->right=NULL;
t->data=e;
}
else if(e>t->data){
Insert(t->left,e);
}
else if(e<t->data){
Insert(t->right,e);
}
}
void Print(BinTree t){
queue<BinTree>q;
q.push(t);
int is=0;
while(!q.empty()){
BinTree temp=q.front();
q.pop();
if(is)cout<<" ";
else is++;
cout<<temp->data;
if(temp->left&&temp->right){
q.push(temp->left);
q.push(temp->right);
if(exs)f=false;
}
else if(temp->left&&!temp->right){
q.push(temp->left);
exs=true;
}
else if(temp->right&&!temp->left){
q.push(temp->right);
f=false;
}
else if(!temp->left&&!temp->right)exs=true;
}
cout<<endl;
if(f)cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
int main()
{
int n,a;
BinTree t=NULL;
cin>>n;
for(int i=0;i<n;i++){
cin>>a;
Insert(t,a);
}
Print(t);
}