Given a sequence, we build a binary search tree, where we use an array to store the tree (the root node is n, then the left son is 2n, and the right son is 2n+1). In the tree building process, we start traversing from the root node each time, Recurse to the left if it encounters a node greater than the root, otherwise recurse to the right, and at the same time we update maxn (used to record the subscript of the array where the last node is located), so that a tree is built
For layer sequence traversal, we can directly output according to the array index to determine whether it is a complete binary tree. We only need to see whether the first n points are in the first n positions of the array.
Code
#include<iostream>#include<cstdio>#include<string>#include<cstring>#include<algorithm>usingnamespace std;constint N =1e5+10;int n, x;int tree[N];intmain(){
cin >> n;int maxn =0;for(int i =0; i < n; i++){
cin >> x;int now =1;//每次从根节点插入while(tree[now]){
if(x > tree[now]){
now = now *2;}else{
now = now *2+1;}}
tree[now]= x;if(now > maxn) maxn = now;}bool flag =true;
cout << tree[1];for(int i =2; i <= maxn; i++){
if(tree[i]) cout <<" "<< tree[i];else flag =false;}
cout << endl;if(flag) cout <<"YES"<< endl;else cout <<"NO"<< endl;return0;}