1123. Is It a Complete AVL Tree (30)
时间限制 400 ms
内存限制 65536 kB
代码长度限制 16000 B
判题程序
Standard 作者 CHEN, Yue
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.
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
tips:真想说是一道树的集大成的题。这次去考试pat甲,前三个题都很顺利,最后全都耗时间在最后一题。
#include<iostream>
#include<queue>
using namespace std;
int n,rt,sz;
int a[110],h[110],f[110];
int t[110][2];
int flag;
int node(int value,int fr)
{
sz++;a[sz]=value;h[sz]=1;f[sz]=fr;return sz;
}
void count(int x)
{
h[x]=max(h[t[x][0]],h[t[x][1]])+1;
}
void rotate(int x,int k)
{
int fr=f[x];int g=f[fr];
t[fr][!k]=t[x][k];if(t[x][k])f[t[x][k]]=fr;
if(g)t[g][fr==t[g][1]]=x;f[x]=g;
t[x][k]=fr;f[fr]=x;
count(fr);count(x);
}
int change(int x)
{
for(int g=f[f[x]];g;g=f[f[x]])
{
count(f[x]);count(g);
if(abs(h[t[g][0]]-h[t[g][1]])>1)
{
int y=x==t[f[x]][0];
int z=f[x]==t[g][0];
y^z?(rotate(x,y),rotate(x,z)):rotate(f[x],z);
}
else x=f[x];
}
while(f[x]){count(x);x=f[x];}
return x;
}
void insert(int &x,int y)
{
if(!x){x=node(y,x);return;}
for(int i=x;;i=t[i][y>a[i]])
{
if(t[i][y>a[i]])continue;
t[i][y>a[i]]=node(y,i);
x=change(t[i][y>a[i]]);
return;
}
}
struct Node{
int index,tag;
};
void bfs()
{
queue<Node>q;
q.push(Node{rt,1});
while(!q.empty())
{
Node tt=q.front();q.pop();
int i=tt.index;int tag=tt.tag;
if(tag>n)flag=1;
if(i==rt)cout<<a[rt];else cout<<" "<<a[i];
if(t[i][0])q.push(Node{t[i][0],tag<<1});
if(t[i][1])q.push(Node{t[i][1],tag<<1|1});
}
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++){
int x;cin>>x;
insert(rt,x);
}
bfs();
if(!flag)cout<<endl<<"YES"<<endl;else cout<<endl<<"NO"<<endl;
return 0;
}