#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
typedef long long ll;
const int maxn = 1e2 + 5, inf = 1e9;
struct node
{
int num;
node *left = nullptr, *right = nullptr;
};
int get_height(node *t)
{
if (t == nullptr)
return 0;
return max(get_height(t->left), get_height(t->right)) + 1;
}
node* leftRotation(node *t)
{
auto tmp = t->right;
t->right = tmp->left;
tmp->left = t;
return tmp;
}
node* rightRotation(node *t)
{
auto tmp = t->left;
t->left = tmp->right;
tmp->right = t;
return tmp;
}
node* leftRightRotation(node *t)
{
t->left=leftRotation(t->left);
return rightRotation(t);
}
node* rightLeftRotation(node *t)
{
t->right=rightRotation(t->right);
return leftRotation(t);
}
void insert_node(node *&t, int num)
{
if (t == nullptr)
{
t = new node;
t->num = num;
return;
}
if (t->num > num)
{
insert_node(t->left, num);
int hl = get_height(t->left), hr = get_height(t->right);
if (hl - hr >= 2)
{
if (t->left->num > num)
t=rightRotation(t);
else
t=leftRightRotation(t);
}
}
else
{
insert_node(t->right, num);
int hl = get_height(t->left), hr = get_height(t->right);
if (hr - hl >= 2)
{
if (t->right->num > num)
t=rightLeftRotation(t);
else
t=leftRotation(t);
}
}
}
void BFS(node *t,int n)
{
queue<node *> q;
q.push(t);
bool flag = true;
while (!q.empty()&&n)
{
auto p = q.front();
q.pop();
if (p != nullptr)
{
cout << p->num;
if (--n)
cout << " ";
q.push(p->left);
q.push(p->right);
}
else
flag = false;
}
cout << (flag ? "\nYES" : "\nNO");
}
int main()
{
int n,tmp;
cin >> n;
node *t = nullptr;
for (int i = 0; i < n; i++)
{
cin >> tmp;
insert_node(t,tmp);
}
BFS(t,n);
return 0;
}
1123 Is It a Complete AVL Tree (30 分)-PTA甲级-AVL树模板题
最新推荐文章于 2024-08-19 18:41:12 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)