将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过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;
vector<int> level(100010, -1);
int n, t, flag, st, cnt;
void build(int val, int root){
if(val > level[root]){
if(level[2 * root + 1] != -1) build(val, 2 * root + 1);
else level[2 * root + 1] = val;
}
else if(val < level[root]){
if(level[2 * root + 2] != -1) build(val, 2 * root + 2);
else level[2 * root + 2] = val;
}
}
int main(){
cin >> n >> t, level[0] = t;
for(int i = 1;i < n;i++) cin >> t, build(t, 0);
for(int i = 0;i < 100010;i++){
if(level[i] != -1){
if(flag++) cout << " ";
cout << level[i];
cnt++;
}else{
if(cnt < n) st = 1;
}
}
if(st) cout << endl << "NO";
else cout << endl << "YES";
}
#include<bits/stdc++.h>
#define ll long long
#define speed_up ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
struct Node{
int data;
Node* left;
Node* right;
};
typedef Node* Tree;
void insert(Tree& B,int x){
if(B==NULL){
B=new(Node);
B->data=x;
B->left=NULL;
B->right=NULL;
}
else if(x>B->data)insert(B->left,x);
else if(x<B->data)insert(B->right,x);
}
bool h;
vector<int>g;
void bfs(Tree B){
queue<Tree>p;
p.push(B);
while(p.size()){
Tree T=p.front();
p.pop();
if(T==NULL){
while(T==NULL&&p.size()){
T=p.front();
p.pop();
}
if(T!=NULL)h=true;
else if(T==NULL)break;
}
g.push_back(T->data);
p.push(T->left);
p.push(T->right);
}
}
int main(){
speed_up
Tree B=NULL;
int x,n;
cin>>n;
for(int i=0;i<n;i++){
cin>>x;
insert(B,x);
}
bfs(B);
if(g.size()>0)
cout<<g[0];
for(int i=1;i<g.size();i++){
if(g[i]>0)
cout<<" "<<g[i];
else h=true;
}
if(g.size())cout<<endl;
if(!h)cout<<"YES";
else cout<<"NO";
}