1123 Is It a Complete AVL Tree (30分)
An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.
F1.jpg F2.jpg
F3.jpg F4.jpg
Now given a sequence of insertions, you are supposed to output the level-order traversal sequence of the resulting AVL tree, and to tell if it is a complete binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤ 20). Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.
Output Specification:
For each test case, insert the keys one by one into an initially empty AVL tree. Then first print in a line the level-order traversal sequence of the resulting AVL tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line. Then in the next line, print YES if the tree is complete, or NO if not.
样例
Sample Input 1:
5
88 70 61 63 65
Sample Output 1:
70 63 88 61 65
YES
Sample Input 2:
8
88 70 61 96 120 90 65 68
Sample Output 2:
88 65 96 61 70 90 120 68
NO
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int N=30;
int n;
int l[N],r[N],v[N],h[N],idx;
int pos[N];
void update(int u)
{
h[u]=max(h[l[u]],h[r[u]])+1;
}
void R(int& u)
{
int p=l[u];
l[u]=r[p],r[p]=u;
update(u),update(p);
u=p;
}
void L(int& u)
{
int p=r[u];
r[u]=l[p],l[p]=u;
update(u),update(p);
u=p;
}
int get_balance(int u)
{
return h[l[u]]-h[r[u]];
}
void insert(int& u,int w)
{
if(!u)
{
u=++idx;
v[u]=w;
}
else if(w<v[u])
{
insert(l[u],w);
if(get_balance(u)==2)
{
if(get_balance(l[u])==1) R(u);
else L(l[u]),R(u);
}
}
else
{
insert(r[u],w);
if(get_balance(u)==-2)
{
if(get_balance(r[u])==-1) L(u);
else R(r[u]),L(u);
}
}
update(u);
}
bool bfs(int root)
{
queue<int> q;
q.push(root);
pos[root]=1;
bool flag=true;
bool res=true;
while(!q.empty())
{
auto t=q.front();
q.pop();
if(pos[t]>n) res=false; //判断是不是完全二叉树
if(flag)
{
cout<<v[t];
flag=0;
}
else cout<<' '<<v[t];
if(l[t]) q.push(l[t]),pos[l[t]]=pos[t]*2;
if(r[t]) q.push(r[t]),pos[r[t]]=pos[t]*2+1;
}
return res;
}
int main()
{
cin>>n;
int root=0;
for(int i=0;i<n;i++)
{
int w;
cin>>w;
insert(root,w);
}
bool res=bfs(root);
cout<<endl;
if(res) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
return 0;
}