A1123 Is It a Complete AVL Tree [avl]
考察知识:avl树建树,判断一棵树是否是完全二叉树,层序遍历输出
白痴bug卡了40分钟!!!!!
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
using namespace std;
const int maxn = 1001;
struct node
{
int v, height;
node* left, * right;
}*root;
node* newnode(int v)
{
node* Node = new node;
Node->v = v;
Node->height = 1;
Node->left = Node->right = NULL;
return Node;
}
int getheight(node* root)
{
if (root == NULL) return 0;
return root->height;
}
void updataheight(node* root)
{
root->height = max(getheight(root->left), getheight(root->right)) + 1;
}
int getbalancefactor(node* root)
{
return getheight(root->left) - getheight(root->right);
}
void l(node* &root)
{
node* temp = root->right;
root->right = temp->left;
temp->left = root;
updataheight(root);
updataheight(temp);
root = temp;
}
void r(node*& root)
{
node* temp = root->left;
root->left = temp->right;
temp->right = root;
updataheight(root);
updataheight(temp);
root = temp;
}
void insert(node*& root, int v)
{
if (root == NULL)
{
root = newnode(v);
return;
}
if (v <root->v)
{
insert(root->left, v);
updataheight(root);
if (getbalancefactor(root) == 2)
{
if (getbalancefactor(root->left) == 1)
r(root);
else if (getbalancefactor(root->left) == -1)
{
l(root->left);
r(root);
}
}
}
else
{
insert(root->right, v);
updataheight(root);
if (getbalancefactor(root) == -2)
{
if (getbalancefactor(root->right) == -1)
l(root);
else if (getbalancefactor(root->right) == 1)
{
r(root->right);
l(root);
}
}
}
}
int main()
{
int n, v;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> v;
insert(root, v);
}
cout << root->v << endl;
return 0;
}