您的位置:首页 > 其它

1123. Is It a Complete AVL Tree (30)

2017-02-27 21:47 387 查看
#include<iostream>
#include<deque>
#include<cstdlib>
using namespace std;
struct node {
int data;
node *l, *r;
int h;
node() {
l = r = NULL;
h = 0;
}
};
int N;
int Geth(node* &p)//求p的h
{
if (p->l == NULL && p->r == NULL)  p->h = 1;
else if (p->l == NULL &&p->r != NULL)p->h = p->r->h + 1;
else if (p->l != NULL  &&p->r == NULL) p->h = p->l->h + 1;
else p->h = p->l->h > p->r->h ? p->l->h + 1 : p->r->h + 1;
return p->h;
}

int differ(node* &p)//求p的平衡读(左子数高度-右子树高度)不能出现绝对值>1
{
if (p->l == NULL && p->r == NULL) return 0;
else if (p->l == NULL &&p->r != NULL)return 0 - p->r->h;
else if (p->l != NULL  &&p->r == NULL)return p->l->h;
else return p->l->h - p->r->h;
return 0;
}
void L_Rotate(node *&p)//左旋
{
node *t = p->r;
p->r = t->l;
Geth(p);
t->l = p;
p = t;
Geth(p);
}
void R_Rotate(node *&p)//右旋
{
node *t = p->l;
p->l = t->r;
Geth(p);
t->r = p;
p = t;
Geth(p);
}
void Insert_node(node *&root, int e)
{
if (root == NULL)
{
root = (node *)malloc(sizeof(node));
root->data = e;
root->l = root->r = NULL;
root->h = 1;
return;
}
if (e == root->data) return;
else if (e > root->data)//R
{
Insert_node(root->r, e);
}
else//L
{
Insert_node(root->l, e);
}
Geth(root);
if (differ(root) > 1)//L
{
switch (differ(root->l))
{
case 1:R_Rotate(root);//LL情况
break;
case -1:
L_Rotate(root->l);//LR情况
R_Rotate(root);
break;
}
}
else if (differ(root) < -1)//R
{
switch (differ(root->r))
{
case -1:L_Rotate(root);//RR情况
break;
case 1:
R_Rotate(root->r);//RL情况
L_Rotate(root);
break;
}
}
}

int main()
{
cin >> N;
node *root = NULL;
for (int t = 0;t < N;t++)
{
int e;
cin >>e;
Insert_node(root,e);
}
int flag = 0,cnt=1;
deque<node *> te;
te.push_back(root);
while (!te.empty())
{
node *p = te.front();
te.pop_front();
if (p == root) cout << p->data;
else cout << " " << p->data;
if (p->l) {
te.push_back(p->l);
cnt++;
}
else
{
if (cnt != N) flag = 1;
}
if (p->r) {
te.push_back(p->r);
cnt++;
}
else
{
if (cnt != N) flag = 1;
}
}
cout << endl;
if (flag ==0) cout << "YES" << endl;
else cout << "NO" << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PAT-甲