题目描述
知识点: 平衡二叉树
思路: 模板题,背住
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int N = 30;
int l[N],r[N],h[N],idx,n,e[N],node[N];
void R(int &u){
int p = l[u];
l[u] = r[p];
r[p] = u;
u = p;
}
void L(int &u){
int p = r[u];
r[u] = l[p];
l[p] = u;
u = p;
}
void update(int u){//更新树高
if(u == 0) return;
update(l[u]);
update(r[u]);
h[u] = max(h[l[u]],h[r[u]])+1;
}
int get_balance(int u){
return h[l[u]] - h[r[u]];
}
void insert(int &u,int x){
if(!u){
u = ++idx;
e[u] = x;
}else{
if(e[u] > x){
insert(l[u],x);
if(get_balance(u) > 1){
if(get_balance(l[u]) >= 1){//LL型
R(u);
}else{
L(l[u]);
R(u);
}
}
}
else{
insert(r[u],x);
if(get_balance(u) < -1){
if(get_balance(r[u]) <= -1){//RR型
L(u);
}else{
R(r[u]);
L(u);
}
}
}
}
update(u);
}
void bfs(int u){
queue<int> q;
q.push(u);
int cur = 1;
cout<<e[u];
while(!q.empty()){
int f = q.front();
q.pop();
if(cur != 1) cout<<" "<<e[f];
node[cur++] = f;
if(l[f]) q.push(l[f]);
if(r[f]) q.push(r[f]);
}
}
int main(){
int root=0;
cin>>n;
for(int i = 0;i < n;i++){
int a;
cin>>a;
insert(root,a);
}
bfs(root);
bool is_complete = true;
for(int i = 1;i <= n;i++){
if(2 * i <= n && e[l[node[i]]] != e[node[2*i]]){
is_complete = false;
break;
}
if(2 * i + 1<= n && e[r[node[i]]] != e[node[2*i+1]]){
is_complete = false;
break;
}
}
if(is_complete) cout<<endl<<"YES";
else cout<<endl<<"NO";
return 0;
}