题目描述:
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输出格式:
将输入的N个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出YES,如果该树是完全二叉树;否则输出NO。
输入样例:
9
38 45 42 24 58 30 67 12 51
输出样例:
38 45 24 58 42 30 12 67 51
YES
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int tree[N];
int _max;
void creat(int root, int num) {
if (!tree[root]) {
tree[root] = num;
_max = max(_max, root);
return;
}
if (tree[root] < num) {
creat(root * 2, num);
} else {
creat(root * 2 + 1, num);
}
}
int main() {
int n; cin >> n;
for (int i = 0; i < n; i++) {
int t; cin >> t;
creat(1, t);
}
for (int i = 1; ; i++) {
if (i == _max) {
cout << tree[i] << endl;
break;
} else if (tree[i] != 0) {
cout << tree[i] << ' ' ;
}
}
if (_max != n) cout << "NO\n";
else cout << "YES\n";
return 0;
}